【发布时间】:2019-10-13 02:04:06
【问题描述】:
考虑以下基本 Python 类:
class Foo(object):
def __init__(self, a1):
self._att1 = a1
@property
def att1(self):
return self._att1
@att1.setter
def att1(self, a):
try:
self._att1 = a
except TypeError:
# handle exception
print("Not allowed")
class Bar(Foo):
def __init__(self):
Foo.__init__(self, 100)
@Foo.att1.setter
def att1(self, a):
# self.att1 = a * 0.5 # RecursionError: maximum recursion depth exceeded
# Foo.att1 = a * 0.5 # attribute is not changed (base instances are though (?))
# Foo.att1(self,a) # TypeError: 'property' object is not callable
super().att1.__set__(a * 0.5) # AttributeError: 'int' object has no attribute '__set__'
# ... some other additional code ...
a = Foo(5)
b = Bar()
b.att1 = 700
print(a.att1)
print(b.att1)
从子类的覆盖中调用基属性设置器的语法是什么?我知道我可以直接设置self._att1,但我想避免这种情况,因为我需要重复异常处理代码。这只是一个简单的例子,我有更复杂的情况,基类在属性上实现了一些额外的操作,我想避免在派生类属性设置器上重复相同的代码。
【问题讨论】:
-
我认为
self._att1 =是个不错的主意。 -
对不起,应该是
Foo.att1.__set__(a)。 -
Foo.att1.__set__(self, a * 0.5) -
@rdas 是的。 @jonrsharpe
__set__抱怨它也需要self参数。 @martineau 我编辑了帖子以包含该尝试 -
@jonrsharpe:我的意思是 OP 在两个类定义之外执行一些代码,我想知道它是什么。
标签: python class properties attributes overriding