在hasattr()上没有eval的Python延迟属性

Tim*_*mol 5 python decorator lazy-evaluation

当你试图访问它时,是否有可能使一个装饰器使属性变得懒惰hasattr()?我弄清楚如何使它变得懒惰,但是hasattr()过早地评估它.例如,

class lazyattribute:
    # Magic.

class A:
    @lazyattribute
    def bar(self):
      print("Computing")
      return 5

>>> a = A()
>>> print(a.bar)
'Computing'
5
>>> print(a.bar)
5
>>> b = A()
>>> hasattr(b, 'bar') 
'Computing'
5
# Wanted output: 5
Run Code Online (Sandbox Code Playgroud)

mik*_*kej 0

问题是hasattr使用getattr,因此当您使用时,您的属性总是会被评估hasattr。如果您发布魔术代码,lazyattribute希望有人可以建议一种测试不需要hasattr或的属性是否存在的替代方法getattr。请参阅帮助hasattr

>>> help(hasattr)
Help on built-in function hasattr in module __builtin__:

hasattr(...)
    hasattr(object, name) -> bool

    Return whether the object has an attribute with the given name.
    (This is done by calling getattr(object, name) and catching exceptions.)
Run Code Online (Sandbox Code Playgroud)