Dynamically bind method to class instance in python

前端 未结 4 1095
野性不改
野性不改 2021-01-06 00:52

Let\'s say that I have a class defined in moduleA.py which I want to add a method to, using some sort of loader method that takes a the name of a second module

4条回答
  •  醉话见心
    2021-01-06 01:09

    Since meth2() is a function, it is a descriptor and you can bind it by calling the __get__() method.

    def meth2(self):
        return self.a + self.b
    
    class ClassA(object):
        def __init__(self,config):
            super(ClassA, self).__init__()
            self.a = 1
            self.b = 2
            self.meth1 = config.__get__(self, ClassA)
    
    c = ClassA(meth2)
    print c.meth1() #correctly prints 3 
    

提交回复
热议问题