python中 super 的用法


参考链接:
https://www.cnblogs.com/python-nameless/p/6229506.html
https://www.jb51.net/article/128571.htm

 


1.  通过super 调用父类方法


class A(object):
    def __init__(self):
        self.n = 10
    def minus(self, m):
        self.n -= m
class B(A):
    def __init__(self):
        super(B, self).__init__()
    def minus(self, m):
        super(B, self).minus(m)
        self.n -= 2
b = B()
b.minus(2)
print b.n

2. Python类中super()和__init__()的关系

 

 

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'>, <class '__main__.childA'>, <class '__main__.childB'>, <class '__main__.Base'>, <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", line 10, in __init__
    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", line 10, in __init__
    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", line 10, in __init__
    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", line 10, in __init__
    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", line 10, in __init__
    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", line 10, in __init__
    super(childC, self).__init__()
  File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__
    super(childC, 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'>, <class '__main__.childA'>, <class '__main__.Base'>, <type 'object'>]
### 回答1: 在Python,`super()`是一个内置函数,它允许子类调用父类的方法。使用`super()`的常见用法是在子类的构造函数调用父类的构造函数以初始化父类的属性。 `super()`的一般语法是 `super(type, object)`。其,`type`是子类名,`object`是子类对象。如果省略了`object`,则默认为`self`。例如: ```python class Parent: def __init__(self, name): self.name = name class Child(Parent): def __init__(self, name, age): super().__init__(name) # 调用父类的构造函数 self.age = age ``` 在上面的例子,`Child`类继承自`Parent`类,通过`super()`函数调用了`Parent`类的构造函数,初始化了`name`属性。 除了在构造函数调用父类的构造函数,还可以使用`super()`方法调用父类的其他方法。例如: ```python class Parent: def __init__(self, name): self.name = name def say_hello(self): print("Hello, " + self.name) class Child(Parent): def __init__(self, name, age): super().__init__(name) def say_hello(self): super().say_hello() # 调用父类的say_hello()方法 print("I'm " + str(self.age) + " years old.") child = Child("Tom", 10) child.say_hello() ``` 在上面的例子,`Child`类继承了`Parent`类的`say_hello()`方法,并通过`super()`函数调用了父类的`say_hello()`方法,然后打印出`I'm 10 years old.`。 ### 回答2: 在Pythonsuper()是一个特殊的内置函数,用于调用父类的方法。它常用于子类,重写父类的方法并在子类调用父类的同名方法。super()函数可以在子类非常方便地访问父类的方法和属性。 super()函数的用法有两种形式。第一种形式是在子类使用super().方法名()的方式调用父类的方法。例如,如果子类重写了父类的方法,可以使用super().父类方法()来调用父类的方法,从而实现在子类添加新功能的同时保留父类原有的功能。 另一种形式是在子类使用super(子类名, self).方法名()的方式调用父类的方法。这种方式主要用于多重继承场景下,当子类有多个父类时,可以指定调用哪个父类的方法。通过传递子类名和self参数给super()函数,可以明确指定使用哪个父类的方法。 使用super()函数的好处是,可以减少父类方法的重复代码,提高代码的可读性和可维护性。它遵循了面向对象编程的原则,将相关的代码封装在类,并实现了代码的复用。 需要注意的是,在Python 2.x版本super()函数的使用需要传递两个参数,分别是子类和self参数。而在Python 3.x版本,可以省略这两个参数,直接使用super().方法名()来调用父类的方法。 ### 回答3: 在Pythonsuper是一个特殊函数,用于调用父类(超类)的方法。它的主要作用是在子类调用父类的方法,以实现继承。super的使用方法有两种: 第一种是在子类的方法使用super(),通过该方式调用父类的方法。例如,假设有一个父类叫做Parent,子类叫做Child,父类有一个方法叫做foo(),我们可以在子类的方法使用super().foo()来调用父类的foo()方法。这样可以避免在子类重复编写与父类方法相同的代码。 第二种是在子类的初始化方法使用super(),通过该方式调用父类的初始化方法。在子类的初始化方法,通常会先调用父类的初始化方法以确保父类的属性初始化完成。例如,假设父类有一个初始化方法叫做__init__(),我们可以在子类的初始化方法使用super().__init__()来调用父类的初始化方法。 需要注意的是,使用super时,如果有多个父类,则按照定义的顺序依次调用。而且,super的使用也不限于两级继承关系,可以用于更复杂的多级继承结构。 总结而言,super的使用在Python非常重要,可以方便地调用父类的方法,避免代码重复,提高代码的可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小金子的夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值