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?