[英]How to define a custom function of an instance using setattr
我試圖動態地向類添加方法,但是我一直遇到一個錯誤,即self
未傳遞給新函數。 例如:
class Dummy():
def say_hi(self):
print("hi")
def new_method(self):
print("bye")
dummy = Dummy()
setattr(dummy, "say_bye", new_method)
dummy.say_bye()
導致以下錯誤:
Traceback (most recent call last):
File "main.py", line 13, in <module>
dummy.say_bye()
TypeError: new_method() missing 1 required positional argument: 'self'
我究竟做錯了什么?
使用types.MethodType
功能:
from types import MethodType
class Dummy():
def say_hi(self):
print("hi")
def new_method(self):
print("bye")
dummy = Dummy()
dummy.say_bye = MethodType(new_method, dummy)
dummy.say_bye() # bye
您正在將函數new_method
設置為dummy
對象的屬性。
如果您進行print(dummy.__dict__)
,則會看到類似以下內容:
{'say_bye': <function new_method at 0x7fcd949af668>}
這意味着您的dummy
對象具有new_method
函數作為屬性,因此當您執行dummy.say_bye()
,您將調用具有作為屬性的函數而沒有任何參數。
它不是Dummy
類的函數,而只是您的dummy
對象具有的函數。
您可以使用RomanPerekhrest的答案來實現所需的功能。
希望能幫助到你。
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.