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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With