Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class inheritance - Base is modified by a subclass

Let's say I have a class called Test with an attribute items. Then I create a subclass called Best. Which has a method that modifies the classes attribute items. But it even modifies Test's items and I what it to modify items only for Best.

class Test():
    items = []

class Best(Test):
    def method(self):
        type(self).items.append("a test")

>>> Best().method()
>>> Best.items
["a test"]
>>> Test.items 
["a test"]            # This is what I don't want.
like image 874
skywalker Avatar asked Feb 28 '26 13:02

skywalker


1 Answers

You have declared items as an attribute of the superclass itself, so all instances of Test and it's subclasses will share the same list. Instead declare it in Test's __ init __ method, so there is one list per instance.

In Best, just append to self.items, and only the Best instance's list will be updated.

class Test(object):
    def __ init __(self)
        self.items = []

class Best(Test):    # Best must inherit from Test
    def method(self):
        self.items.append("a test")
like image 85
snakecharmerb Avatar answered Mar 03 '26 02:03

snakecharmerb