简体   繁体   English

Python super()继承和需要的参数

[英]Python super() inheritance and needed arguments

Considering: 考虑到:

class Parent(object):

    def altered(self):
        print "PARENT altered()"

class Child(Parent):

    def altered(self):
        print "CHILD, BEFORE PARENT altered()"
        super(Child, self).altered()    # what are the arguments needed?  Why Child and self?
        print "CHILD, AFTER PARENT altered()"

In Python 2.7, Why must Child be passed as an argument to the super() call? 在Python 2.7中,为什么必须将Child作为参数传递给super()调用? What are the exact intricacies of using super instead of just letting it work. 使用超级而不仅仅是让它工作的确切错综复杂是什么。

super figures out which is the next class in the Method Resolution Order. super数字是方法解决顺序中的下一个类。 The two arguments you pass in are what lets it figure that out - self gives it the entire MRO via an attribute; 你传递的两个参数是什么让它想出来 - self通过一个属性给它整个MRO; the current class tells it where you are along the MRO right now . 现在的班级告诉你现在你在MRO的哪个地方。 So what super is actually doing is basically: 那么超级实际上做的基本上是:

def super(cls, inst):
    mro = inst.__class__.mro() # Always the most derived class
    return mro[mro.index(cls) + 1]

The reason it is the current class rather than the base class is because the entire point of having super is to have a function that works out what that base class is rather than having to refer to it explicitly - which can cause problems if the base class' name changes, if you don't know exactly what the parent class is called (think of factory functions like namedtuple that spit out a new class), and especially in multi-inheritance situations (where the next class in the MRO mightn't be one of the current class' bases). 它是当前类而不是基类的原因是因为拥有super的整个要点是拥有一个能够解决该基类的函数而不必明确地引用它 - 这可能会导致基类的问题'名称更改,如果您namedtuple地知道父类被调用了什么(想想像吐出一个新类的namedtuple这样的工厂函数),特别是在多继承情况下(MRO中的下一个类可能不会)是当前班级的基地之一。

You don't have to pass the child instance as an argument from python3 onwards if I'm not mistaken. 如果我没有弄错的话,你不必从python3开始将子实例作为参数传递。 Plus for an in-depth understanding of the super() method refer to https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ 另外,要深入了解super()方法,请参阅https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM