1

If I have a child class that inherits from a base class whose init() adds an item to an array, as follows:

class TestBaseClass : 
    arr = []

    def __init__(self) : 
        print self.arr
        self.arr.append(1)
        print self.arr
        return

class TestChildClass1(TestBaseClass) : 
    foo = 1

Then I find it strange that when I instantiate the child class twice,

test1 = TestChildClass1()
test2 = TestChildClass1()

the second one seems to not have an empty array but contains the value 1 that was added by the first.

Why is that base class instance shared by the two and not created as a new instance? This does not seem to be intuitively how one would expect inheritance to behave.

1 Answers1

0
class TestBaseClass : 
    arr = []

Here, you are creating a class variable, not an instance variable. So, this will be shared by all instances of the class. To create instance variables, better add the member variable to the current object in the initializer function (__init__) like this

def __init__(self):
    self.arr = []
    ...

Since we add arr to the current object (self), whenever you create an object of the class, new variable will be created.

thefourtheye
  • 221,210
  • 51
  • 432
  • 478
  • Wrong answer, even in case of instance variables, the same variable will be shared among derived classes – SEDaradji Jul 31 '17 at 17:10