描述问题
以前以为自己知道super怎么用,但是看到下面的代码,却是没有搞懂其作用原理
下面的代码,神奇地做到了"属性设置不能为int" (实现在父类里面)
查阅了super的用法,摘抄如下
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type) -> unbound super object
super(type, type2) -> bound super object; requires issubclass(type2, type) #这种用法没见过
Typical use to call a cooperative superclass method:
摘录官方文档如下 (就是第二个参数为type时,不太明白那一段英文的意思)
super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.
If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods).
上下文环境
Python3
重现
相关代码
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
# 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) ##??? 这种用法第一次见, 作用原理/作用流程是什么?
#返回一个父类的实例,然后调用其方法
#关键是: super(SubPerson, SubPerson) 如何使用的?
@name.deleter
def name(self):
print('Deleting name')
super(SubPerson, SubPerson).name.__delete__(self)
报错信息