Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python二级继承_Python_Inheritance - Fatal编程技术网

Python二级继承

Python二级继承,python,inheritance,Python,Inheritance,我对python有点陌生,但我有一个关于二级继承的问题 我有这样的情况: class A: def Something(self): #Do Stuff class B(A): def SomethingElse(self): #Do other stuff class C(B): def Something(self): #Do additional stuff 请注意,类C继承自B,B继承自A,但类B未实现方法Something() 如果我为类

我对python有点陌生,但我有一个关于二级继承的问题

我有这样的情况:

class A:
  def Something(self):
     #Do Stuff

class B(A):
  def SomethingElse(self):
     #Do other stuff

class C(B):
  def Something(self):
     #Do additional stuff
请注意,类C继承自B,B继承自A,但类B未实现方法Something()

如果我为类C的实例调用super(C,self).Something(),会发生什么?它会从类A调用该方法吗

另外,如果类B确实实现了Something(),但我想直接从类C调用类A的Something()(即绕过类B的实现),我该怎么做

最后,有人能解释一下为什么人们使用super()而不是直接调用父类的方法吗?谢谢

  • 是的,它将从
    A
    类调用
    Something()
  • 您可以随时从
    C
    调用
    A.Something(self)

  • 解释
    super()
    和其他调用约定需要一些时间。看一看关于和的原始文章。

    在第一种情况下,如果B没有实现
    某个东西
    ,调用
    super
    将取决于定义它的位置,即
    a

    在第二种情况下,您可以通过调用
    A.Something(self)
    绕过B

    使用
    super
    的主要原因是针对那些具有多重继承的情况:Python将始终调用MRO(方法解析顺序)中的下一个定义

    请参阅雷蒙德·海廷格的优秀文章