Python superuser methods

There are many questions about usage super(), but none of them answer my question.

When called super().__init__()from a subclass, all method calls in the super constructor are actually taken from the subclass. Consider the following class structure:

class A (object):
    def __init __ (self):
        print ("initializing A")
        self.a ()
    def a (self):
        print ("Aa ()")

class B (A):
    def __init __ (self):
        super () .__ init __ ()
        # add stuff for B
        self.bnum = 3 # required by Ba ()        
    def a (self):
        print ("Ba (), bnum =% i"% self.bnum)

b = B ()

which fails with

initializing A
Traceback (most recent call last):
  File "classmagic.py", line 17, in 
    b = B ()
  File "classmagic.py", line 11, in __init__
    super().__init__()
  File "classmagic.py", line 5, in __init__
    self.a()
  File "classmagic.py", line 15, in a
    print("B.a(), bnum=%i"%self.bnum)
AttributeError: 'B' object has no attribute 'bnum'

B() ( a()). , a(), A, , A B .

, , , A , ?

+5
4

, , , :

class A(object):
    def __init__(self):
        print("initializing A")
        self.__a()
    def __a(self):
        print("A.a()")

class B(A):
    def __init__(self):
        super().__init__()
        # add stuff for B
        self.bnum=3 # required by B.a()        
    def __a(self):
        print("B.__a(), bnum=%i"%self.bnum)

Python "mangles" , ( ), , .

Python PEP 8 :

, , . Python, . .

1: , name, , , .

2: , __getattr__(), . .

3: . .

+4

self.a() A.a(self). , , B A.

+2

:

class B(A):
    def __init__(self):
        A.__init__(self)

, super().__init__(). , , self.a(), , , a B, a, self B. , , .

0

B:

  • super(B,self).__init__, A.__init__
  • self.a(), B.a()
  • self.bnum

, bnum ... , AttributeError.

, bnum B.__init__ super(B,self).__init__

class B(A):
    def __init__(self):
       self.bnum=3
       super(B, self).__init__()

, , : , ?

0

All Articles