简体   繁体   English

如何使用setattr定义实例的自定义函数

[英]How to define a custom function of an instance using setattr

I'm trying to add a method to a class dynamically, but I keep running into an error where self is not passed to a the new function. 我试图动态地向类添加方法,但是我一直遇到一个错误,即self未传递给新函数。 For instance: 例如:

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()

results in the following error: 导致以下错误:

Traceback (most recent call last):
  File "main.py", line 13, in <module>
    dummy.say_bye()
TypeError: new_method() missing 1 required positional argument: 'self'

What am I doing wrong? 我究竟做错了什么?

Use types.MethodType feature: 使用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

You are setting the function new_method as an attribute of the dummy object. 您正在将函数new_method设置为dummy对象的属性。

If you do print(dummy.__dict__) you'll see something like this: 如果您进行print(dummy.__dict__) ,则会看到类似以下内容:

{'say_bye': <function new_method at 0x7fcd949af668>}

This means that your dummy object has the function new_method as an attribute, so when you do dummy.say_bye() , you're calling the function you have as an attribute without any argument. 这意味着您的dummy对象具有new_method函数作为属性,因此当您执行dummy.say_bye() ,您将调用具有作为属性的函数而没有任何参数。

It is not a function of the Dummy class, it is just a function that your dummy object has as an attribute. 它不是Dummy类的函数,而只是您的dummy对象具有的函数。

You can achieve the functionality you are looking for using RomanPerekhrest's answer. 您可以使用RomanPerekhrest的答案来实现所需的功能。

Hope it helps. 希望能帮助到你。

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM