简体   繁体   English

python3:使用.__ get __()将类方法绑定到类实例,但是为什么呢?

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

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
        print(self.var)
>>> class MyClass:
        var = 5
>>> c = MyClass()
>>> c.print_var = print_var

this indeed would cause print_var to behave like a normal function, so the self argument wouldn't have his typical meaning: 这确实会导致print_var像普通函数一样运行,因此self参数不具有其典型含义:

>>> c.print_var
<function print_var at 0x98e86ec>
>>> c.print_var()
Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    c.print_var()
TypeError: print_var() takes exactly 1 argument (0 given)

In order to let the function be considered a method (ie to bind it to the instance), I used to use this code: 为了让函数被认为是一个方法(即将它绑定到实例),我曾经使用过这段代码:

>>> import types
>>> c.print_var = types.MethodType(print_var, c)
>>> c.print_var
<bound method MyClass.print_var of <__main__.MyClass object at 0x98a1bac>>
>>> c.print_var()
5

but I found that .__get__ may also be used for this purpose: 但我发现.__get__也可用于此目的:

>>> c.print_var = print_var.__get__(c)
>>> c.print_var
<bound method MyClass.print_var of <__main__.MyClass object at 0x98a1bac>>
>>> c.print_var()
5

The problem here is that it just works, but I can't understand how and why. 这里的问题是它只是有效,但我无法理解如何以及为什么。 The documentation about .__get__ doesn't seem to help very much. 关于.__get__的文档似乎.__get__帮助。

I'd appreciate if someone could clarify this behaviour of python's interpreter. 如果有人能澄清python的解释器的这种行为,我会很感激。

The information you're looking for is in the Descriptor HowTo Guide : 您正在寻找的信息在Descriptor HowTo指南中

To support method calls, functions include the __get__() method for binding methods during attribute access. 为了支持方法调用,函数包括用于在属性访问期间绑定方法的__get__()方法。 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: 在纯Python中,它的工作原理如下:

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. 所以真的没有什么奇怪的事情 - 函数对象的__get__方法调用types.MethodType并返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM