python3: bind method to class instance with .__get__(), it works but why?

前端 未结 1 1637
-上瘾入骨i
-上瘾入骨i 2021-02-20 12:57

I know if you want to add a method to a class instance you can\'t do a simple assignment like this:

>>> def print_var(self): # method to be added
               


        
1条回答
  •  一生所求
    2021-02-20 13:21

    The information you're looking for is in the Descriptor HowTo Guide:

    To support method calls, functions include the __get__() method for binding methods during attribute access. This means that all functions are non-data descriptors which return bound or unbound methods depending whether they are invoked from an object or a class. In pure Python, it works like this:

    class Function(object):
        . . .
        def __get__(self, obj, objtype=None):
            "Simulate func_descr_get() in Objects/funcobject.c"
            return types.MethodType(self, obj)
    

    So there really isn't anything strange going on -- the __get__ method of a function object calls types.MethodType and returns the result.

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