【发布时间】:2021-10-22 06:42:25
【问题描述】:
我有一个 python 数据类,我想根据一些全局变量有条件地分配某些装饰器。
在脚本顶部检查条件,但对于下面的示例,我只是提供了该检查的结果。如果检查是True,我想给这些方法@functools.cached_property 装饰器。如果是False,我只希望他们收到标准的@property 装饰器。
我一直遇到的问题是我无法完全弄清楚如何(或者甚至可能)使它作为一个简单的装饰器工作。在调用或操作test.x_times_y 时,我通常会收到有关方法对象的错误,并且我不确定是否可以编写函数,使得在下面的示例中调用test.x_times_y 实际上会产生我想要的结果。
import functools
import dataclasses
_value_checked = False
def myDecorator(func):
def decorator(self):
if not _value_checked:
return property(func)(self)
else:
return functools.cached_property(func)(self)
return decorator
@dataclasses.dataclass
class MyClass():
x: int
y: int
z: int = 0
@myDecorator
def x_times_y(self):
return self.x*self.y
test = MyClass(5,6,7)
我还想避免使用 getter 和 setter 方法,所以我希望这是可能的。我在这里查看了很多答案(例如this one),但无法找到实际有效的答案,因为大多数不适用于装饰方法。我为此使用 Python 3.8。
【问题讨论】:
-
为什么不
myDecorator = functools.cached_property if _value_checked else property?
标签: python python-3.x properties python-decorators python-dataclasses