Dynamically bind method to class instance in python

前端 未结 4 1097
野性不改
野性不改 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

    There's actually a much simpler way to do this:

    class ClassA(object):
        def __init__(self,config):
            super(ClassA, self).__init__()
    
            self.a = 1
            self.b = 2
    
        from moduleB import meth2 as meth1
    
        def calling_method():
            return self.meth1()
    

提交回复
热议问题