我对代码'self.funcGet'感到困惑,因为它引用了'get'函数,该函数不受类或实例的约束< / strong>。 谁能解释我在这个除湿器中看到的陌生感
class Desc:
def __init__(self,funcGet):
self.funcGet = funcGet #funcGet -> get
def __get__(self,instance,owner):
return self.funcGet(instance) #self.funcGet(instance) -> get(instance)
#return instance.__class__.get(instance) #same as code above, this is what I caught in mind
class Test:
def get(self):
return 'wow'
prop = Desc(get)
a = Test()
print(a.prop) #This call __get__ in Desc Class
输出为
wow
答案 0 :(得分:0)
在此行:
return self.funcGet(instance)
您只是从Test类中调用“ get”函数(此步骤未绑定)并返回结果(“哇”字符串)。
按“。”从描述符(应在其中进行绑定)触发的__get__
访问
要绑定实例,您应该使用:
return self.funcGet.__get__(instance)