【问题标题】:Implementing bound method using descriptor使用描述符实现绑定方法
【发布时间】:2013-04-14 22:55:47
【问题描述】:

我的问题与绑定方法对象有关,更具体地说,我试图模仿函数(本质上是描述符)存在的相同行为。

首先让我在这里说明我对 class_instance.function() 工作原理的理解

Class D(object):
    def dfunc(self):
        ...

d=D()
d.dfunc() # will call D.__dict__['dfunc'].__get__(d,D)()

#gives a bound method which can be used directly
a=D.__dict__['dfunc'].__get__(d,D) 
a() #works as d.D()

如果type(dfunc) 是函数,Python 是否调用D.__dict__['dfunc'] (d),如果x 是类实例,是否调用type(d).__dict__['dfunc'].__get__(d, type(d))

现在来看看我是如何尝试使用闭包创建绑定对象的:

class E(object):
    def __get__(self,obj,cls):

        def returned(*args):
            print(obj.__dict__)
        return returned

class F(object):
    e=E()
    y=9

f=F()
f.fvar=9 #putting something in instances __dict__
a=f.e #will call the __get__ function of F and return a closure
a() #works and produces instance specific result -> {'fvar': 9}, just like a bound method

现在主要问题是, 当我做a=D.__dict__['dfunc'].__get__(d,D) type(a) 时是绑定方法,但是当我实现它时type(a) 是函数;有没有办法从用户定义的描述符中返回绑定对象?

有没有更好的方法来实现像描述符这样的功能? 如果我的头脑中有一些根本不正确的东西,请纠正我。

【问题讨论】:

    标签: python descriptor


    【解决方案1】:

    如果你想返回一个方法,你可以从函数对象和传递给__get__的参数一起创建一个:

    import types
    
    class E(object):
        def __get__(self,obj,cls):
    
            def returned(*args):
                print(obj.__dict__)
            return types.MethodType(returned, obj, cls)
    

    但是,尚不清楚这会给您带来什么。如果只是返回一个函数已经可以工作,为什么还需要它是一个“真正的”方法?

    【讨论】:

    • 随着更改,当我调用 f.e(f 是具有 e 作为属性的类 F 的实例,e 是 E 的实例)时,它给出错误 TypeError: method expected 2 arguments, got 3.
    • 我用的是Python3.3,可能是这个原因
    • 这是完美的(至少在 Python 2.7 中)我看到返回对象的 im_self 和 im_func 设置正确。你知道如何在 3.3 中做到这一点
    猜你喜欢
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2013-03-15
    • 2012-04-29
    • 2015-05-11
    • 1970-01-01
    相关资源
    最近更新 更多