在 python 中,我可以使用 @classmethod
装饰器向类添加一个方法。是否有类似的装饰器来为类添加属性?我可以更好地展示我在说什么。
class Example(object):
the_I = 10
def __init__( self ):
self.an_i = 20
@property
def i( self ):
return self.an_i
def inc_i( self ):
self.an_i += 1
# is this even possible?
@classproperty
def I( cls ):
return cls.the_I
@classmethod
def inc_I( cls ):
cls.the_I += 1
e = Example()
assert e.i == 20
e.inc_i()
assert e.i == 21
assert Example.I == 10
Example.inc_I()
assert Example.I == 11
我在上面使用的语法是可能的还是需要更多的东西?
我想要类属性的原因是我可以延迟加载类属性,这似乎很合理。
原文由 deft_code 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是我将如何做到这一点:
设置器在我们调用
Bar.bar
时不起作用,因为我们正在调用TypeOfBar.bar.__set__
,而不是Bar.bar.__set__
。添加元类定义解决了这个问题:
现在一切都会好起来的。