如何制作一个类属性?

如何制作一个类属性?

在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

我上面使用的语法是可能的还是需要更多的东西?

我想要类属性的原因是我可以延迟加载类属性,这似乎足够合理。


拉丁的传说
浏览 444回答 3
3回答

哆啦的时光机

如果您定义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会覆盖属性对象本身。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python