为了账号安全,请及时绑定邮箱和手机立即绑定

如何制作一个类属性?

如何制作一个类属性?

拉丁的传说 2019-08-12 16:27:54
如何制作一个类属性?在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会覆盖属性对象本身。


查看完整回答
反对 回复 2019-08-12
  • 3 回答
  • 0 关注
  • 443 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信