【发布时间】:2015-09-30 08:04:00
【问题描述】:
我正在尝试对 python 类进行子类化并使用 @property 函数覆盖常规属性。问题是我无法修改父类,子类的 api 需要看起来与父类相同(但行为不同)。 (所以我的问题与this one 不同,this one 的父类也使用了@property 方法来访问底层属性。)
最简单的例子是
# assume this class can't be overwritten
class Parent(object):
def __init__(self, a):
self.attr = a
# how do I make this work?
class Child(Parent):
def __init__(self, a):
super(Child, self).__init__(a)
# overwrite access to attr with a function
@property
def attr(self):
return super(Child, self).attr**2
c = Child(4)
print c.attr # should be 16
这会在调用父 init 方法时产生错误。
<ipython-input-15-356fb0400868> in __init__(self, a)
2 class Parent(object):
3 def __init__(self, a):
----> 4 self.attr = a
5
6 # how do I make this work?
AttributeError: can't set attribute
希望很清楚我想要做什么以及为什么。但我不知道怎么做。
【问题讨论】:
-
您还需要为您的属性编写一个 setter。你读过关于属性的the documentation 吗?但是,我认为您尝试的方法不起作用,因为
self.attr存储在实例上,而不是类上,因此以您似乎尝试的方式使用super无济于事。
标签: python properties subclass