从 Python 3.8 开始,functools有一个cached_property. 我一直在使用lazyprop基于 Beazley 的食谱(下面的代码)的类似装饰器,但是当我用内置函数替换时,我遇到了问题。这是其中之一。
当我在类定义中使用装饰器时,使用@运算符,它不会抱怨。
但是,如果我将它与 一起使用setattr,我会得到:
TypeError: Cannot use cached_property instance without calling __set_name__ on it.
Beazley 的简单版本虽然工作正常。
from functools import cached_property
class lazyprop:
"""Based on code from David Beazley's "Python Cookbook"."""
def __init__(self, func):
self.__doc__ = getattr(func, '__doc__')
self.func = func
def __get__(self, instance, cls):
if instance is None:
return self
else:
value = instance.__dict__[self.func.__name__] = self.func(instance)
return value
class D:
def __init__(self, greeting='Hello'):
self.greeting = greeting
def greet(self):
return self.greeting + " world!"
# Beazley's version works...
D.greet = lazyprop(greet)
assert D().greet == "Hello world!"
# ... but the builtin version will fail
D.greet = cached_property(greet)
# D().greet # this will fail
元芳怎么了
呼唤远方
相关分类