python之super的使用小结

为什么需要super

在python没有引入super之前, 如果需要在子类中引用父类的方法, 一般写法如下:

class Father:
 def whoami(self):
  print("I am father")

class Child:
 def whoami(self):
  print("I am child")
  Father.whoami(self)

这样看好像没什么问题, 就算没有super也能正常调用父类的方法, 但是如果有一天Father类需要修改类名为Father1, 那么子类Child中也必须跟着修改.

想象下如果一个类有很多个子类, 这样一来我们就需要修改每个子类中引用父类的语句

怎么使用super

Help on class super in module builtins:

class super(object)
 | super() -> same as super(__class__, <first argument>)
 | super(type) -> unbound super object
 | super(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的帮助文档, 首先super是一个类, 它的调用方法有如下几种:

1.super()
2.super(type)
3.super(type, obj)
4.super(type, type2)

我们推荐用第一种方法来使用super, 因为它并不需要显式传递任何参数.但是要注意一点, super只能在新式类中使用.

class A:
 def __init__(self):
  print("this is A")

class B(A):
 def __init__(self):
  super().__init__()
  print("this is B")

b = B()

"""
this is A
this is B
"""

看起来super就像直接调用了B的父类A的__init__, 其实并不是这样的, 我们看看super在多继承下的使用

class A:
 def __init__(self):
  print("this is A")
  print("leave A")

class B(A):
 def __init__(self):
  print("this is B")
  super().__init__()
  print("leave B")

class C(A):
 def __init__(self):
  print("this is C")
  super().__init__()
  print("leave C")

class D(B, C):
 def __init__(self):
  print("this is D")
  super().__init__()
  print("leave D")  

d = D()

"""
this is D
this is B
this is C
this is A
leave A
leave C
leave B
leave D
"""

print(D.__mro__)
"""
(<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.C'>,
<class '__main__.A'>,
<class 'object'>)
"""

这里可以看到, 如果super只是简单调用父类的方法的话, 那么调用了B的__init__ 方法之后, 应该调用A的__init__ 才对, 但是调用的却是C的__init__ 方法

这是因为super调用的是当前类在MRO列表中的后一个类, 而并不是简单地调用当前类的父类

python并没有强制性限制我们使用super调用父类, 我们还是可以使用原始的方法来调用父类中的方法, 但是需要注意的是调用父类的方法要统一, 即全用super或全不用super, 而用super 的话, 调用的方式也最好是统一的

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Python中super()函数简介及用法分享

    首先看一下super()函数的定义: super([type [,object-or-type]]) Return a **proxy object** that delegates method calls to a **parent or sibling** class of type. 返回一个代理对象, 这个对象负责将方法调用分配给第一个参数的一个父类或者同辈的类去完成. parent or sibling class 如何确定? 第一个参数的__mro__属性决定了搜索的顺序, sup

  • Python中super函数用法实例分析

    本文实例讲述了Python中super函数用法.分享给大家供大家参考,具体如下: 这是个高大上的函数,在python装13手册里面介绍过多使用可显得自己是高手 23333. 但其实他还是很重要的. 简单说, super函数是调用下一个父类(超类)并返回该父类实例的方法. 这里的下一个的概念参考后面的MRO表介绍. help介绍如下: super(type, obj) -> bound super object; requires isinstance(obj, type) super(type)

  • 深入解析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

  • python类中super()和__init__()的区别

    单继承时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).__

  • 深入理解Python中的super()方法

    前言 python的类分别有新式类和经典类,都支持多继承.在类的继承中,如果你想要重写父类的方法而不是覆盖的父类方法,这个时候我们可以使用super()方法来实现 python语言与C++有相似的类继承,在类定义时,python中会自定义第一个self,类似C++中this指针,指向对象自身. python简单的类举例: >>> class hello(object): ... def print_c(): ... print"hello world!" >&g

  • Python编程中对super函数的正确理解和用法解析

    当在子类需要调用父类的方法时,在python2.2之前,直接用类名调用类的方法,即非绑定的类方法,并把自身对象self作参数传进去. class A(object): def say(self): print 'I am A' class B(A): def say(self): print 'I am B' A.say(self) b = B() b.say() 输出 I am B I am A 这样运作挺好,不过有个问题,当父类改了名字时,就要把这些显式调用父类的一个个更正,子类和父类耦合比

  • Python中super函数的用法

    描述 super() 函数用于调用下一个父类(超类)并返回该父类实例的方法. super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO).重复调用(钻石继承)等种种问题. MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表. 语法 以下是 super() 方法的语法: super(type[, object-or-type]) 参数 type -- 类. object-or-type -- 类,一般是 se

  • Python中的super用法详解

    一.问题的发现与提出 在Python类的方法(method)中,要调用父类的某个方法,在Python 2.2以前,通常的写法如代码段1: 代码段1: 复制代码 代码如下: class A:   def __init__(self):    print "enter A"    print "leave A" class B(A):   def __init__(self):    print "enter B"    A.__init__(sel

  • Python中的super()方法使用简介

    子类里访问父类的同名属性,而又不想直接引用父类的名字,因为说不定什么时候会去修改它,所以数据还是只保留一份的好.其实呢,还有更好的理由不去直接引用父类的名字, 这时候就该super()登场啦-- class A: def m(self): print('A') class B(A): def m(self): print('B') super().m() B().m() 当然 Python 2 里super() 是一定要参数的,所以得这么写: class B(A): def m(self): p

  • Python中super关键字用法实例分析

    本文实例讲述了Python中super关键字用法.分享给大家供大家参考.具体分析如下: 在Python类的方法(method)中,要调用父类的某个方法,在Python 2.2以前,通常的写法如代码段1: 代码段1: class A: def __init__(self): print "enter A" print "leave A" class B(A): def __init__(self): print "enter B" A.__init

  • Python中super的用法实例

    super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO).重复调用(钻石继承)等种种问题.总之前人留下的经验就是:保持一致性.要不全部用类名调用父类,要不就全部用 super,不要一半一半. 普通继承 复制代码 代码如下: class FooParent(object):      def __init__(self):          self.parent = 'I\'m the parent.'         

随机推荐