super python 类本身有什么意义吗?

问题描述 投票:0回答:1

看python代码哪个super函数指向类本身,这个函数有必要吗?如果注释该行(或删除,如果你喜欢:)),结果不会改变。那么这条线实际上是做什么的?

class A():
    def __init__(self, id):
        super(A, self).__init__()
        self.id=id
python class inheritance
1个回答
0
投票

在本例中,超类是

object
,其
__init__
并没有真正做太多事情。如果
A
有一个不平凡的超类,那么它可能会产生很大的影响。

class Superclass:
  def __init__(self):
    # Super important initialization happens here
    ...

class A(Superclass):
  def __init__(self):
    super(A, self).__init__()
    ...

在这种情况下,超级调用非常确实很重要,因为

Superclass.__init__
不会被调用。

顺便说一句,

super
的2参数形式适用于高级用例或十多年前为古代版本的Python编写的代码。对于大多数用例(包括这个),没有显式参数的
super().__init__()
就足够了,而且更干净。

© www.soinside.com 2019 - 2024. All rights reserved.