为什么用super(type1,type2).var .__ set __()覆盖Python子类中的父属性?

时间:2019-03-21 00:40:53

标签: python properties override super

我正在阅读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

0 个答案:

没有答案