如何制作一个类属性?在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我上面使用的语法是可能的还是需要更多的东西?我想要类属性的原因是我可以延迟加载类属性,这似乎足够合理。
3 回答

哆啦的时光机
TA贡献1779条经验 获得超6个赞
如果您定义classproperty
如下,那么您的示例完全按照您的请求工作。
class classproperty(object): def __init__(self, f): self.f = f def __get__(self, obj, owner): return self.f(owner)
需要注意的是,您不能将其用于可写属性。虽然e.I = 20
会引发一个AttributeError
,但Example.I = 20
会覆盖属性对象本身。
添加回答
举报
0/150
提交
取消