加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 是否可以重写子类中属性的getter?

发布时间:2020-12-20 11:18:57 所属栏目:Python 来源:网络整理
导读:例如: class Example: def __init__(self): self.v = 0 @property def value(self): return self.v @value.setter def value(self,v): self.v = vclass SubExample(Example): pass 是否有可能只在SubExample中重写getter值? 解决方法 你可以这样做 class D
例如:

class Example:
    def __init__(self):
        self.v = 0

    @property
    def value(self):
        return self.v
    @value.setter
    def value(self,v):
        self.v = v

class SubExample(Example):
    pass

是否有可能只在SubExample中重写getter值?

解决方法

你可以这样做

class DoubleExample(Example):
    @Example.value.getter
    def value(self):
        return self.v * 2

o = Example()
o.value = 1
print o.value # prints "1"

p = DoubleExample()
p.value = 1
print p.value # prints "2"

但是,这仅适用于Example是一个新样式类(类Example(object):)而不是旧样式类(类Example :),因为它在您的示例代码中.

警告:Thomas在评论中指出,如果您使用多重继承(类Foo(Bar,Baz)),此方法可能无法按预期运行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读