What is super (type) in python?

Class definition:

class A(object):
    def foo(self):
        print "A" 


class B(object):
    def foo(self):
        print "B" 


class C(A, B): 
    def foo(self):
        print "C"

Output:

>>> super(C)
<super: <class 'C'>, NULL>
>>> super(C).foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'super' object has no attribute 'foo'

What is the use of super (type) if we cannot access class attributes?

+4
source share
3 answers

super(type)is a "disconnected" super object. The docs on super discuss this, but do not really specify what a “disconnected” super object is. It is simply a fact that you cannot use them the way you try to use them.

This is perhaps what you want:

>>> super(C, C).foo is B.foo
True

, -? , . , , , , (, , ). :

, . . , super (C1) , c1 :

>>> c1 = C1()
>>> boundsuper = super(C1).__get__(c1, C1) # this is the same as super(C1, c1)

, , :

, , , . , super(C) . . :

>>> class B(object):
...     a = 1
>>> class C(B):
...     pass
>>> class D(C):
...     sup = super(C)
>>> d = D()
>>> d.sup.a
1

, d.sup.a super(C).__get__(d,D).a, super(C, d).a B.a.

super, , , , . - , .

, . , __sup C super(C):

>>> C._C__sup = super(C)

, ( , , - , MRO , , , , , X X, ).

+7

, , :

>>> myC = C()
>>> super(C,myC).foo()
A
+1

, NULL - . , .

>>> super(C, C()).foo
<bound method C.foo of <__main__.C object at 0x225dc50>>

: Python super() __init __() .

0
source

Source: https://habr.com/ru/post/1532761/


All Articles