深入理解python super
发布日期:2021-06-29 16:00:29 浏览次数:2 分类:技术文章

本文共 2011 字,大约阅读时间需要 6 分钟。

我们在中,谈到了这样一个问题,在python 3.6

super(C, C).__init__Out[108]: 

而在,python 2.7里面是这样的

>>> super(C, C).__init__

这是因为在python 3.x中已经没有unbound method这样的概念了。在python 3.x中,如果对象调用方法的话,会返回一个函数对象,如果你对于functionmethod的区别困惑的话,可以去阅读。

在文章的末尾留下了一个疑问:

python2.7>>> print super.__doc__super(type, obj) -> bound super object; requires isinstance(obj, type)super(type) -> unbound super objectsuper(type, type2) -> bound super object; requires issubclass(type2, type)Typical use to call a cooperative superclass method:class C(B):    def meth(self, arg):        super(C, self).meth(arg)python3.6>>> print(super.__doc__)super() -> same as super(__class__, 
)super(type) -> unbound super objectsuper(type, obj) -> bound super object; requires isinstance(obj, type)super(type, type2) -> bound super object; requires issubclass(type2, type)Typical use to call a cooperative superclass method:class C(B): def meth(self, arg): super().meth(arg)This works for class methods too:class C(B): @classmethod def cmeth(cls, arg): super().cmeth(arg)

为什么文档中说super(type, type)是一个bound,但是我们在之前的测试中得到的是这样的结果

>>> super(C, C).__init__

其实原因在于,我始终忽略了一个细节,就是文档中说的bound super object,也就是说它是一个绑定的super对象,而不是一个unbound method

method一样,既然有bound super object,那么就一定有unbound super object,根据文档上的叙述,就是通过super(type)实现unbound super object

那么我们这样super(C).__init__调用会返回什么呢?会是unbound method吗?有了前面的基础,我想你这个时候应该不会轻易地下这样的结论了。

>>> super(C).__init__

那么什么是method-warpper呢?

python 3.x,你可以将它理解为通过C实现的bound method。至于python 2.7,(+_+)?

另外,unbound super object可以通过下面这种方式转化为bound super objectpython 2.7

>>> super(C).__get__(C, C)
,
>>>> super(C).__get__(c, C)
,
>>>> super(C, C)
,
>>>> super(C, c)
,
>

如果在python 3.x的话

super(C).__get__(C, C)Out[23]: 
super(C).__get__(c, C)Out[24]:
>super(C, C)Out[25]:
super(C, c)Out[26]:
>

至此你应该对于super对象有一个大概的映像了,并且你也就清楚了简介中所说的描述符是一个强大的通用协议,它们是属性,方法,静态方法,类方法和super()的工作机制

转载地址:https://coordinate.blog.csdn.net/article/details/79531891 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Ubuntu16.04+1080ti+cuda9.0+cudnn7.04+tensorflow1.6配置
下一篇:python描述符使用指南

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月07日 15时18分30秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章