what does <class 'super'>class do in python?

This question already has an answer here:

  • Understanding Python super() with __init__() methods [duplicate] 7 answers

  • super(Child, self).__init__() <=> SomeBaseClass.__init__(self)
    

    It provides a nice shorthand for calling a method on the parent class without having to type it explicitly, which can be long (programmers are lazy) and error-prone. If you change your code later such that Child is not a SomeBaseClass anymore but a AnotherBaseClass instead, you don't have to change the call to the constructor (which is itself required as it will not be called by default)

    Note that the case here is obvious, since there is only one base class, but in case where there is an ambiguity (eg two or more parent classes), mro prevails (as you would expect I suppose, since that's what it is about):

    >>> class A(object):
    ...     def __init__(self):
    ...         print "A"
    ... 
    >>> class B(object):
    ...     def __init__(self):
    ...         print "B"
    ... 
    >>> class C(A, B):
    ...     def __init__(self):
    ...         super(C, self).__init__()
    ...             print "C"
    ... 
    >>> c = C()
    A
    C
    >>> class D(B, A):
    ...     def __init__(self):
    ...         super(D, self).__init__()
    ...             print "D"
    ... 
    >>> d = D()
    B
    D
    >>> class CC(A, B):
    ...     def __init__(self):
    ...         B.__init__(self) # Explicitely call B and not A !
    ...         print "CC"
    ... 
    >>> cc = CC()
    B
    CC
    

    super(Child, self).__init__()
    

    Means: Call the method __init__ of the base type of Child with the instance self . So in your case, this would be equivalent to SomeBaseClass.__init__(self) . But using super lets you avoid explicitely naming the base type again and also works for multiple inheritance.

    So super(t, self) basically means get the base type(s) of the type t , and bind it to the instance self so you can call methods directly.

    Note that in Python 3, the arguments to super() are optional, so super().__init__() works.


    __init__() is the constructor in python, and super is the parent class which you inherit your class from.

    class Child(SomeBaseClass):
        def __init__(self):
            super(Child, self).__init__()
    

    For this code whenever you insatiate a new object of type Child it will call its constructor __init__() which in its turn calls SomeBaseClass.__init__().

    链接地址: http://www.djcxy.com/p/30042.html

    上一篇: 什么是功能

    下一篇: <class'super'> class在python中做了什么?