我是 python 的新手,我有一些 python 代碼與 dll 庫(在 C 中)介面。我的 python 代碼現在作業正常,但我被告知將一些初始化實作到它們自己的函式中。例如,我目前擁有的是:
你好.py
import ctypes
class my_outer_class:
def __init__(self):
test = ctypes.WinDLL('C:\\Users\OneDrive\HelloWorld\HelloWorld\loc\Debug\HelloWorld.dll')
self.py_function_1 = test.function_1
self.py_function_1.argtype = (ctypes.c_uint8,ctypes.c_uint8 )
self.py_function_1.restype = ctypes.c_int
self.py_function_2 = test.function_2
self.py_function_2.argtype = (ctypes.c_uint8,ctypes.c_uint8 )
self.py_function_2.restype = ctypes.c_int
運行_test.py
import hello
import ctypes
myapi = hello.my_outer_class()
result = myapi.py_function_1(123,123)
print(result)
result = myapi.py_function_2(123,123)
print(result)
我想知道是否可以將我的 hello.py 更改為:
你好.py
import ctypes
class my_outer_class:
def __init__(self):
test = ctypes.WinDLL('C:\\Users\OneDrive\HelloWorld\HelloWorld\loc\Debug\HelloWorld.dll')
def func_1(self):
self.py_function_1 = test.function_1
self.py_function_1.argtype = (ctypes.c_uint8,ctypes.c_uint8 )
self.py_function_1.restype = ctypes.c_int
def func_2(self):
self.py_function_2 = test.function_2
self.py_function_2.argtype = (ctypes.c_uint8,ctypes.c_uint8 )
self.py_function_2.restype = ctypes.c_int
運行_test.py
import hello
import ctypes
myapi = hello.my_outer_class()
result = myapi.func_1(123,123)
print(result)
result = myapi.func_2(123,123)
print(result)
當我運行修改后的版本時,出現錯誤:
Traceback (most recent call last):
File "C:\Users\OneDrive\run_test.py", line 6, in <module>
result = myapi.func_1(123,123)
AttributeError: 'my_outer_class' object has no attribute 'func_1'
>>>
我感謝任何建議,謝謝。
將 hello.py 修改為
import ctypes
class my_outer_class:
def __init__(self):
self.test = ctypes.WinDLL('C:\\Users\giova\OneDrive\Escritorio\HelloWorld\HelloWorld\loc\Debug\HelloWorld.dll')
def func_1(self, var1, var2):
self.py_function_1 = self.test.function_1
self.py_function_1.argtype = (ctypes.c_uint8,ctypes.c_uint8 )
self.py_function_1.restype = ctypes.c_int
def func_2(self, var1, var2):
self.py_function_2 = self.test.function_2
self.py_function_2.argtype = (ctypes.c_uint8,ctypes.c_uint8 )
self.py_function_2.restype = ctypes.c_int
和 run_test.py
import hello
import ctypes
myapi = hello.my_outer_class()
result = myapi.func_1(123,123)
print(result)
result = myapi.func_2(123,123)
print(result)
此時我沒有收到任何錯誤,我得到了這個輸出
None
None
>>>
而不是 1 和 0 的預期值。我能夠在我的代碼的第一個版本中獲得這些值。“self”旁邊的其他兩個引數也需要匹配我在 argtype 下的引數嗎?例如
def func_1(self, ctypes.c_uint8, ctypes.c_uint8):
因為我嘗試過這種方式,但它給了我一個無效的語法錯誤。
def func_1(self, ctypes.c_uint8, ctypes.c_uint8):
^
SyntaxError: invalid syntax
uj5u.com熱心網友回復:
本質上,您在這里遇到了縮進問題。
請在您的類中重新縮進您的 func x 以使它們可從外部訪問。這是一個簡短的說明:
class my_outer_class:
def __init__(self):
print("initiated")
def func_1(self):
print("Hello FUNC_1")
def func_2(self):
print("Hello FUNC_2")
myapi = my_outer_class()
myapi.func_1()
myapi.func_2()
要更深入地了解 Python 中的類和面向物件編程,您可以從以下內容開始:https : //python-textbok.readthedocs.io/en/1.0/Classes.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364028.html
上一篇:單個鏈表節點內的多個資料
