python super函数1008无标题_关于Python的super用法一处不解

描述问题

以前以为自己知道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)

a8a3adfb02b969fda9ef0e4b7b7d9cc9.png

报错信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值