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')
print(self)
self._name = value
# Deleter function
@name.deleter
def name(self):
raise AttributeError("Can't delete attribute")
class SubPerson(Person):
@property
def name(self):
print('Getting name')
return super().name
@name.setter
def name(self, value):
print('Setting name to', value)
super(SubPerson, SubPerson).name.__set__(self, value)
@name.deleter
def name(self):
print('Deleting name')
super(SubPerson, SubPerson).name.__delete__(self)
s = SubPerson('Guido')
print(s.name)
当我super(SubPerson, SubPerson).name.__set__(self, value)
到<
super(SubPerson, self).name.__set__(self, value)
,我得到了这个问题
AttributeError: 'SubPerson' object has no attribute '_name'
为什么?
答案 0 :(得分:0)
super(SubPerson, SubPerson)
是访问SubPerson
的重写属性的代理,但super(SubPerson, self)
是访问 self
的重写属性的代理。通过这种方式,我的意思是,当它通过类dicts搜索属性查找时,它会对实例属性而不是类属性执行描述符处理。
super(SubPerson, self).name
在name
中找到Person.__dict__
属性。然后自动调用__get__
。 getter试图阅读self._name
,它不存在,因此你的错误。