我遇到以下错误:
Traceback (most recent call last):
File ".../TEST.py", line 34, in <module>
b.level = 12 # Error
File ".../TEST.py", line 23, in level
super().level(self, new_level)
TypeError: 'int' object is not callable
这是代码:
class A:
def __init__(self):
self._level = 0
@property
def level(self):
return self._level
@level.setter
def level(self, new_level):
self._level = new_level
class B(A):
def __init__(self):
super().__init__()
@property
def level(self):
return self._level
@level.setter
def level(self, new_level):
super().level(self, new_level)
a = A()
print(a.level) # --> 0
a.level = 12
print(a.level) # --> 0
b = B()
print(b.level) # --> 12
b.level = 12 # Error
print(b.level) # never reached
我看到了该帖子class method TypeError "Int object not callable",但对我没有帮助
答案 0 :(得分:1)
答案 1 :(得分:0)
我能想到的最好的是:
setter中没有代码:setter只调用其他方法
2.a执行setter指令的已定义实例方法
2.b由设置员调用
class A:
def __init__(self):
self._level = 0
def A_level_setter(self, new_level): # 2.a
print('Setter instructions of A')
self._level = new_level
@property
def level(self):
return self._level
@level.setter
def level(self, new_level):
self.A_level_setter(new_level) # 2.b
class B(A):
def B_level_setter(self, new_level): # 2.a
print('Setter instructions of B')
self.A_level_setter(new_level)
@A.level.setter # 1.
def level(self, new_level):
self.B_level_setter(new_level) # 2.b
class C(A):
pass
a = A()
print(a.level) # 0
b = B()
print(b.level) # 0
c = C()
print(c.level) # 0
a.level = 1 # Setter instructions of A
print(a.level) # 1
b.level = 2 # Setter instructions of A
# Setter instructions of B
print(b.level) # 2
c.level = 3 # Setter instructions of A
print(c.level) # 3
答案 2 :(得分:0)
另一个答案似乎是最好的答案:
class B(A):
@A.level.setter
def level(self, new_level):
super(B, type(self)).level.fset(self, new_level)