Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about behaviour of base class

Tags:

python

This follows a question I asked a few hours ago.

I have this code:

class A(object):
    def __init__(self, a):
        print 'A called.'
        self.a = a

class B(A):
    def __init__(self, b, a):
        print 'B called.'

x = B(1, 2)
print x.a

This gives the error: AttributeError: 'B' object has no attribute 'a', as expected. I can fix this by calling super(B, self).__init__(a).

However, I have this code:

class A(object):
    def __init__(self, a):
        print 'A called.'
        self.a = a

class B(A):
    def __init__(self, b, a):
        print 'B called.'
        print a

x = B(1, 2)

Whose output is:

B called.
2

Why does this work? And more importantly, how does it work when I have not initialized the base class? Also, notice that it does not call the initializer of A. Is it because when I do a:

def __init__(self, b, a)

I am declaring b to be an attribute of B? If yes, how can I check b is an attribute of which class - the subclass or the superclass?

like image 470
Jeremy Avatar asked Feb 26 '23 06:02

Jeremy


1 Answers

The way you defined it B does not have any attributes. When you do print a the a refers to the local variable a in the __init__ method, not to any attribute.

If you replace print a with print self.a you will get the same error message as before.

like image 162
sepp2k Avatar answered Mar 07 '23 02:03

sepp2k