Assign external function to class variable in Python

后端 未结 1 408
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-19 04:27

I am trying to assign a function defined elsewhere to a class variable so I can later call it in one of the methods of the instance, like this:

from module impor         


        
相关标签:
1条回答
  • 2021-02-19 05:06

    Python functions are descriptor objects, and when attributes on a class accessing them an instance causes them to be bound as methods.

    If you want to prevent this, use the staticmethod function to wrap the function in a different descriptor that doesn't bind to the instance:

    class Bar(object):
        func = staticmethod(my_func)
        def run(self):
            self.func()
    

    Alternatively, access the unbound function via the __func__ attribute on the method:

    def run(self):
        self.func.__func__()
    

    or go directly to the class __dict__ attribute to bypass the descriptor protocol altogether:

    def run(self):
        Bar.__dict__['func']()
    

    As for math.pow, that's not a Python function, in that it is written in C code. Most built-in functions are written in C, and most are not descriptors.

    0 讨论(0)
提交回复
热议问题