栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在派生类中调用super()时,可以传递self .__ class__吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在派生类中调用super()时,可以传递self .__ class__吗?

你不能。该

super()
调用需要知道该方法属于哪个类,以在基类中搜索被覆盖的方法。

如果您在传递

self.__class__
(或更好,
type(self)
)则
super()
给出 错误的 出发点,以寻找方法,并最终调用_再次它自己的方法_ 。

在构成方法解析顺序序列的类列表中,将其视为指针。如果传入,

type(self)
则指针将引用任何子类,而不是原始起点。

以下代码导致无限递归错误:

class base(object):    def method(self):        print 'original'class Derived(base):    def method(self):        print 'derived'        super(type(self), self).method()class Subclass(Derived):    def method(self):        print 'subclass of derived'        super(Subclass, self).method()

演示:

>>> Subclass().method()subclass of derivedderivedderivedderived<... *many* lines removed ...>  File "<stdin>", line 4, in method  File "<stdin>", line 4, in method  File "<stdin>", line 4, in methodRuntimeError: maximum recursion depth exceeded while calling a Python object

因为

type(self)
Subclass
没有
Derived
Derived.method()

在这个例子中,MRO为

Subclass
[Subclass, Derived,base]
,而
super()
需要知道从哪里开始寻找任何替代的方法。通过使用
type(self)
它告诉它从开始
Subclass
,所以它将
Derived.method()
在我们开始的地方找到下一个。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470489.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号