如何制作一个类属性?
在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 += 1e = Example()assert e.i == 20e.inc_i()assert e.i == 21assert Example.I == 10Example.inc_I()assert Example.I == 11
我上面使用的语法是可能的还是需要更多的东西?
我想要类属性的原因是我可以延迟加载类属性,这似乎足够合理。
哆啦的时光机
相关分类