调用时在Python描述符属性上的问题

问题描述 投票:0回答:1

我对代码'self.funcGet'感到困惑,因为它引用的是'get'函数,该函数不受类或实例的束缚谁能解释我在此除湿器中看到的奇怪之处

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
python class descriptor
1个回答
0
投票

在该行:

return self.funcGet(instance)

您只是从Test类中调用'get'函数(此步骤未绑定)并返回结果(“哇”字符串)。

按“。”访问您从描述符触发的__get__(应在其中进行绑定)

要绑定实例,您应该使用:

return self.funcGet.__get__(instance)
© www.soinside.com 2019 - 2024. All rights reserved.