I have a piece of python code:
class A(object):
args = [1,2]
def __init__(self):
print self.args
class B(A):
args = [3,4]
def __init__(self):
super(B, self).__init__()
print self.args
B()
The output is:
[3, 4]
[3, 4]
and not
[1,2]
[3,4]
How come when calling the constructor of a base class from a derived class, the class attributes used is from the namespace of the derived class? Is there a way for me to use the class attributes of the class in which the function resides in?
What's occurring here is that you've overwritten the
args
variable with B's member instead essentially. Python first looks at the the sub-class B to see if it can printargs
with its own version with A's constructor. It finds B'sargs
and prints that member instead.Lets see what happens when you rename A's
args
to something else likearg
. We now see the behavior that was expected.Output: