美文网首页胶水Python
Python:super函数

Python:super函数

作者: 爱折腾的大懒猪 | 来源:发表于2019-04-29 22:26 被阅读2次

    这是个高大上的函数,在python装13手册里面介绍过多使用可显得自己是高手 23333. 但其实他还是很重要的. 简单说, super函数是调用下一个父类(超类)并返回该父类实例的方法. 这里的下一个的概念参考后面的MRO表介绍.

    help介绍如下:

    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:
    class C(B):
        def meth(self, arg):
            super(C, self).meth(arg)
    

    由此可知, super有三种用法, 第一参数总是召唤父类的那个类, 第二参数可缺(返回非绑定父类对象),也可以是实例对象或该类的子类. 最终返回的都是父类的实例(绑定或非绑定). 在Python3中,super函数多了一种用法是直接super(),相当于super(type,首参), 这个首参就是一般的传入的self实例本身啦. 因为在py2里面常用也是这种写法.

    另外, 在py2中, super只支持新类( new-style class, 就是继承自object的).

    为什么要调用父类?

    相关文章

      网友评论

        本文标题:Python:super函数

        本文链接:https://www.haomeiwen.com/subject/jlkpnqtx.html