2

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?

jerrypeng
  • 104
  • 1
  • 5
  • `self.attribute` first looks at the "direct" attributes of the object and then walks the inheritance chain up until it finds the attribute. When you do `self.args` it first "looks at self", than looks at B and finds the attribute. – syntonym Dec 16 '16 at 21:30

2 Answers2

1

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
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

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]
ospahiu
  • 3,465
  • 2
  • 13
  • 24