Python using class attributes with super when inheriting

55 views Asked by At

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?

2

There are 2 answers

0
ospahiu On

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 print args with its own version with A's constructor. It finds B's args and prints that member instead.

Lets see what happens when you rename A's args to something else like arg. We now see the behavior that was expected.

class A(object):
    arg = [1,2]
    def __init__(self):
        print self.arg

class B(A):
    args = [3,4]
    def __init__(self):
        super(B, self).__init__()
        print self.args
B()

Output:

[1, 2]
[3, 4]
0
Robᵩ On

Is there a way for me to use the class attributes of the class in which the function resides in?

Yes. Refer to them by their class attribute name and not their instance attribute name. That is, A.args, not self.args.

class A(object):
    args = [1,2]
    def __init__(self):
        print A.args