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)
when i make the super(SubPerson, SubPerson).name.__set__(self, value)
to
super(SubPerson, self).name.__set__(self, value)
, i get this issue
AttributeError: 'SubPerson' object has no attribute '_name'
Why?
super(SubPerson, SubPerson)
is a proxy to access overridden attributes of SubPerson
, but super(SubPerson, self)
is a proxy to access overridden attributes of self
. By this, I mean that while it searches through class dicts for attribute lookup, it performs descriptor handling for instance attributes rather than class attributes.
super(SubPerson, self).name
finds the name
property in Person.__dict__
. It then calls __get__
automatically. The getter tries to read self._name
, which doesn't exist, hence your error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.