我正在阅读Python食谱,并在8.8章有疑问。在SubPerson中,为什么以下代码在setter函数中不起作用? super()。name =值 或超级(SubPerson,SubPerson)。名称=值
如果您查看SubPerson中的getter函数,则super()。name确实起作用。为什么?
class Person:
def __init__(self, name):
self.name = name
# Getter function
@property
def name(self):
return self._name
# Setter function
@name.setter
def name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._name = value
class SubPerson(Person):
@property
def name(self):
print('Getting name')
return super().name # Why super().name works here?
@name.setter
def name(self, value):
print('Setting name to', value)
super(SubPerson, SubPerson).name.__set__(self, value)
#super().name = value ... This statement gets error
#super(SubPerson, SubPerson).name = value ...Get Error