python3:使用.__ get __()将方法绑定到类实例,它可以工作,但是为什么呢? [英] python3: bind method to class instance with .__get__(), it works but why?

查看:108
本文介绍了python3:使用.__ get __()将方法绑定到类实例,它可以工作,但是为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果您想将方法添加到类实例中,您将无法像这样进行简单的分配:

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.

推荐答案

您要查找的信息位于

为支持方法调用,函数包括__get__()方法,用于在属性访问期间绑定方法.这意味着所有函数都是非数据描述符,它们返回绑定方法或非绑定方法,具体取决于是从对象还是从类调用它们.在纯Python中,它的工作方式如下:

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)

所以实际上没有什么奇怪的-函数对象的__get__方法调用types.MethodType并返回结果.

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

这篇关于python3:使用.__ get __()将方法绑定到类实例,它可以工作,但是为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆