我正在動態編程環境中工作,我可能需要定義(或重新定義)類函數。所以考慮這個例如:在類定義之外的Python函數分配會導致參數異常
def func(self):
print("hello2 \n")
class ManClass:
def __init__(self):
pass
def func1(self):
print("hello1\n")
a = ManClass()
a.func1()
hello1
a.func2 = func
>>> a.func2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes exactly 1 argument (0 given)
如果FUNC2()已定義在類內部 - a.func2()會被解釋爲ManClass.func2(一) - 但現在,我在外面給它分配,它似乎期待一個論點。我如何解決這個問題,但更重要的是,爲什麼這兩個定義之間存在差異?
哦,你說得對。類和實例屬性/函數是「不同的」。我應該知道我做錯了什麼。非常感謝 ! – user1922297