如何在实例化时动态地将函数添加到python中的实例

use*_*508 2 python metaprogramming setattr

如果我有一个python类,它允许在实例化时有一个options参数,我怎样才能根据该options参数的值动态设置一个函数.例如,如果我有代码

def hello1():
    print(self.name,"says hi")

def hello2():
    print(self.name,"says hello")

class A:
    def __init__(self, name, opt=0):
        if opt == 1:
            setattr(self,'hello',hello1)
        else:
            setattr(self,'hello',hello2)

if __name__ == "__main__":
    a1 = A("my")
    a2 = A("name",1)
    a1.hello()
    a2.hello()
Run Code Online (Sandbox Code Playgroud)

我收到了追溯错误

Traceback (most recent call last):
  File "dynamic_classes.py", line 17, in <module>
    a1.hello()
  File "dynamic_classes.py", line 5, in hello2
    print(self.name,"says hello")
NameError: global name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

您的函数不定义self参数,也不会获取参数.

你需要使用方法 ; 您可以通过将它们视为描述符并显式调用.__get__()它们来从函数中创建它们:

def hello1(self):
    print(self.name,"says hi")

def hello2(self):
    print(self.name,"says hello")

class A:
    def __init__(self, name, opt=0):
        if opt == 1:
            setattr(self, 'hello', hello1.__get__(self, type(self))
        else:
            setattr(self, 'hello', hello2.__get__(self, type(self)))
Run Code Online (Sandbox Code Playgroud)

通常,在(直接或通过实例).__get__()访问函数时调用该函数.但是,直接在实例上添加的函数不会发生这种情况,因此您需要手动执行此操作.