微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

深入解析Python编程中super关键字的用法

官方文档中关于super的定义说的不是很多,大致意思是返回一个代理对象让你能够调用一些继承过来的方法,查找的机制遵循mro规则,最常用的情况如下面这个例子所示:

class C(B):
  def method(self,arg):
    super(C,self).method(arg)

子类C重写了父类B中同名方法method,在重写的实现中通过super实例化的代理对象调用父类的同名方法

super类的初始方法签名如下:

def __init__(self,type1,type2=None): # kNown special case of super.__init__
    """
    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:

除去self外接受一个或者或者两个参数,如同注释声明的一样,接受两个参数时返回的是绑定的super实例,省略第二个参数的时候返回的是未绑定的super对象。

一般情况下当调用继承的类方法或者静态方法时,并不需要绑定具体的实例,这个时候使用super(type,type2).some_method就能达到目的,当然super(type,obj)在这种情况下也能够使用,super对象有自定义实现的getattribute方法也能够处理。不过,后者一般用来调用实例方法,这样在查找方法的时候能够传入相应的实例,从而得到绑定的实例方法

class A(object):
  def __init__(self):
    pass

  @classmethod
  def klass_meth(cls):
    pass

  @staticmethod
  def static_meth():
    pass

  def test(self):
    pass

class B(A):
  pass

>>> b = B()
>>> super(B,b).test
<bound method B.test of <__main__.B object at 0x02DA3570>>
>>> super(B,b).klass_meth
<bound method type.klass_meth of <class '__main__.B'>>
>>> super(B,b).static_meth
<function static_meth at 0x02D9CC70>
>>> super(B,B).test
<unbound method B.test>
>>> super(B,B).klass_meth
<bound method type.klass_meth of <class '__main__.B'>>
>>> super(B,B).satic_meth
>>> super(B,B).static_meth
<function static_meth at 0x02D9CC70>

初始化super对象的时候,传递的第二个参数其实是绑定的对象,第一个参感觉数可以粗暴地理解为标记查找的起点,比如上面例子中的情况:super(B,b).test就会在B.__mro__里面列出的除B本身的类中查找方法test,因为方法都是非数据描述符,在super对象的自定义getattribute里面实际上会转化成A.__dict['test'].__get__(b,B)。

super在很多地方都会用到,除了让程序不必hardcode指定类型让代码更加动态,还有其他一些具体必用的地方比如元类中使用super查找baseclass里面的new生成自定义的类型模板;在自定义getattribute的时候用来防止无限循环等等。

关于super建议读者将它与python的描述符一起来理解,因为super就实现了描述符的协议,是一个非数据描述符,能够帮助大家更好的理解super的使用和工作原理。

同时,有以下4个点值得大家注意:
1、单继承时super()__init__()实现的功能是类似的

class Base(object):
  def __init__(self):
    print 'Base create'

class childA(Base):
  def __init__(self):
    print 'creat A ',Base.__init__(self)


class childB(Base):
  def __init__(self):
    print 'creat B ',super(childB,self).__init__()

base = Base()

a = childA()
b = childB()

输出结果:

Base create
creat A Base create
creat B Base create


使用super()继承时不用显式引用基类。

2、super()只能用于新式类

把基类改为旧式类,即不继承任何基类

class Base():
  def __init__(self):
    print 'Base create'

执行时,在初始化b时就会报错:

  super(childB,self).__init__()
TypeError: must be type,not classobj

3、super不是父类,而是继承顺序的下一个

    在多重继承时会涉及继承顺序,super()相当于返回继承顺序的下一个类,而不是父类,类似于这样的功能

def super(class_name,self):
  mro = self.__class__.mro()
  return mro[mro.index(class_name) + 1]

    mro()用来获得类的继承顺序。

例如:

class Base(object):
  def __init__(self):
    print 'Base create'

class childA(Base):
  def __init__(self):
    print 'enter A '
    # Base.__init__(self)
    super(childA,self).__init__()
    print 'leave A'


class childB(Base):
  def __init__(self):
    print 'enter B '
    # Base.__init__(self)
    super(childB,self).__init__()
    print 'leave B'

class childC(childA,childB):
  pass

c = childC()
print c.__class__.__mro__

输入结果如下:

enter A 
enter B 
Base create
leave B
leave A
(<class '__main__.childC'>,<class '__main__.childA'>,<class '__main__.childB'>,<class '__main__.Base'>,<type 'object'>)

    supder和父类没有关联,因此执行顺序是A ―> B―>―>Base

    执行过程相当于:初始化childC()时,先会去调用childA的构造方法中的 super(childA,self).__init__(), super(childA,self)返回当前类的继承顺序中childA后的一个类childB;然后再执行childB().__init()__,这样顺序执行下去。

    在多重继承里,如果把childA()中的 super(childA,self).__init__() 换成Base.__init__(self),在执行时,继承childA后就会直接跳到Base类里,而略过了childB:

enter A 
Base create
leave A
(<class '__main__.childC'>,<type 'object'>)

 

    从super()方法可以看出,super()的第一个参数可以是继承链中任意一个类的名字,

    如果是本身就会依次继承下一个类;

    如果是继承链里之前的类便会无限递归下去;

    如果是继承链里之后的类便会忽略继承链汇总本身和传入类之间的类;

    比如将childA()中的super改为:super(childC,self).__init__(),程序就会无限递归下去。

    如:

 File "C:/Users/Administrator/Desktop/crawler/learn.py",line 10,in __init__
  super(childC,self).__init__()
 File "C:/Users/Administrator/Desktop/crawler/learn.py",self).__init__()
RuntimeError: maximum recursion depth exceeded while calling a Python object

4、super()可以避免重复调用

    如果childA基础Base,childB继承childA和Base,如果childB需要调用Base的__init__()方法时,就会导致__init__()被执行两次:

class Base(object):
  def __init__(self):
    print 'Base create'

class childA(Base):
  def __init__(self):
    print 'enter A '
    Base.__init__(self)
    print 'leave A'


class childB(childA,Base):
  def __init__(self):
    childA.__init__(self)
    Base.__init__(self)

b = childB()
  Base的__init__()方法被执行了两次

enter A 
Base create
leave A
Base create
使用super()是可避免重复调用

class Base(object):
  def __init__(self):
    print 'Base create'

class childA(Base):
  def __init__(self):
    print 'enter A '
    super(childA,self).__init__()
    print 'leave A'


class childB(childA,Base):
  def __init__(self):
    super(childB,self).__init__()

b = childB()
print b.__class__.mro()

enter A 
Base create
leave A
[<class '__main__.childB'>,<type 'object'>]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用爬虫利器 Playwright,轻松爬取抖查查数据 我们先分析登录的接口,其中 url 有一些非业务参数:ts、he、sign、secret。 然后根据这些参数作为关键词,定位到相关的 js 代码。 最后,逐步进行代码的跟踪,发现大部分的代码被混淆加密了。 花费了大半天,来还原这些混淆加密的代码
轻松爬取灰豚数据的抖音商品数据 调用两次登录接口实现模拟登录 我们分析登录接口,发现调用了两次不同的接口;而且,需要先调用 https://login.huitun.com/weChat/userLogin,然后再调用 https://dyapi.huitun.com/userLogin 接口。 登
成功绕过阿里无痕验证码,一键爬取飞瓜数据 飞瓜数据的登录接口,接入了阿里云的无痕验证码;通过接口方式模拟登录,难度比较高。所以,我们使用自动化的方式来实现模拟登录,并且获取到 cookie 数据。 [阿里无痕验证码] https://help.aliyun.com/document_detail/1
一文教你从零开始入门蝉妈妈数据爬取,成功逆向破解数据加密算法 通过接口进行模拟登录 我们先通过正常登录的方式,分析对应的登录接口。通过 F12 打开谷歌浏览器的调试面板,可以看到登录需要传递的一些参数;其中看到密码是被加密了。 不过我们通过经验可以大概猜测一下,应该是通过 md5 算法加密了。 接下
抽丝剥茧成功破解红人点集的签名加密算法 抽丝剥茧破解登录签名算法,成功实现模拟登录 headers = {} phone_num = &quot;xxxx&quot; password = &quot;xxxx&quot; md5_hash = hashlib.md5() md5_hash.upda
轻松绕过 Graphql 接口爬取有米有数的商品数据 有米有数数据的 API 接口,使用的是一种 API 查询语言 graphql。所有的 API 只有一个入口,具体的操作隐藏在请求数据体里面传输。 模拟登录,获取 sessionId 调用登录接口,进行模拟登录。 cookies = {} head
我最近重新拾起了计算机视觉,借助Python的opencv还有face_recognition库写了个简单的图像识别demo,额外定制了一些内容,原本想打包成exe然后发给朋友,不过在这当中遇到了许多小问题,都解决了,记录一下踩过的坑。 1、Pyinstaller打包过程当中出现warning,跟d
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Pooling在中文当中的意思是“池化”,在神经网络当中非常常见,通常用的比较多的一种是Max Pooling,具体操作如下图: 结合图像理解,相信你也会大概明白其中的本意。不过Pooling并不是只可以选取2x2的窗口大小,即便是3x3,
记得大一学Python的时候,有一个题目是判断一个数是否是复数。当时觉得比较复杂不好写,就琢磨了一个偷懒的好办法,用异常处理的手段便可以大大程度帮助你简短代码(偷懒)。以下是判断整数和复数的两段小代码: 相信看到这里,你也有所顿悟,能拓展出更多有意思的方法~
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic histogram2. 数据分布与密度信息显示 Control rug and density on seaborn histogram3. 带箱形图的直方图 Histogram with a boxplot on t