我的问题与绑定(bind)方法对象有关,更具体地说,我试图模仿函数(本质上是描述符)存在的相同行为。
让我先把我对 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()
Python 是否调用 D.__dict__['dfunc'] (d),以防 type(dfunc) 是函数且 type(d)。 __dict__['dfunc'].__get__(d, type(d)) 如果 x 是类实例?
现在介绍我如何尝试使用闭包创建绑定(bind)对象:
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) 是绑定(bind)方法时,但是当我实现它时 type(a) 是函数;有没有办法从用户定义的描述符返回绑定(bind)对象?
有没有更好的方法来实现像描述符这样的函数? 如果我脑子里有什么根本性的错误,请纠正我。
请您参考如下方法:
如果你想返回一个方法,你可以从函数对象和传递给 __get__ 的参数创建一个:
import types
class E(object):
def __get__(self,obj,cls):
def returned(*args):
print(obj.__dict__)
return types.MethodType(returned, obj, cls)
但是,您并不完全清楚这会给您带来什么。如果仅仅返回一个函数就已经有效,为什么你需要它是一个“真正的”方法?
