【问题标题】:Issue on Python Descriptor attribute when called调用时出现 Python 描述符属性问题
【发布时间】:2020-01-01 04:01:29
【问题描述】:

我对代码 '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

【问题讨论】:

  • 这不是绑定方法,而是您手动提供实例。我不确定我明白你在问什么,你能澄清一下这个问题吗?你期待什么?
  • @MSeifert 我希望'self.funcGet'是'get'。所以当它返回 self.funcGet(instance) 时,它看起来像 get(instance),没有类。并感谢您的评论。我尊重它。 :)

标签: python class descriptor


【解决方案1】:

行内:

return self.funcGet(instance)

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

按“。”访问你从描述符中触发了__get__(应该在哪里绑定)

要绑定你应该使用的实例:

return self.funcGet.__get__(instance)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 2012-10-02
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多