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
这确实会导致print_var
的行为类似于普通函数,因此self
参数将没有他的典型含义:
this indeed would cause print_var
to behave like a normal function, so the self
argument wouldn't have his typical meaning:
>>> 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 (i.e. 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
但我发现.__get__
也可以用于此目的:
but I found that .__get__
may also be used for this purpose:
>>> 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
这里的问题是它可以工作,但是我不知道如何以及为什么.有关 .__get__
似乎并没有太大帮助.
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.
如果有人能澄清python解释器的这种行为,我将不胜感激.
I'd appreciate if someone could clarify this behaviour of python's interpreter.