How work pre-defined descriptors in functions?

后端 未结 1 331
悲&欢浪女
悲&欢浪女 2021-01-12 17:01

Python functions have a descriptors. I believe that in most cases I shouldn\'t use this directly but I want to know how works this feature? I tried a couple of manipulations

相关标签:
1条回答
  • 2021-01-12 17:35

    a.__get__ is a way to bind a function to an object. Thus:

    class C(object):
        pass
    
    def a(s):
        return 12
    
    a = a.__get__(C)
    

    is the rough equivalent of

    class C(object):
        def a(self):
            return 12
    

    (Though it's not a good idea to do it this way. For one thing, C won't know that it has a bound method called a, which you can confirm by doing dir(C). Basically, the __get__ does just one part of the process of binding).

    That's why you can't do this for a function that takes no arguments- it must take that first argument (traditionally self) that passes the specific instance.

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