Child class attributes point to the same object reference from parent

Viewed 69

Basing on the code below, I had expected student.hobbies to be separate from player.hobies, but it seems they both point to the same reference object and performing an operation on one affects the other.

class Person:
    hobbies = []

class Student(Person):
    pass

class Player(Person):
    pass

student = Student()
player = Player()

student.hobbies.append("Reading")
player.hobbies.append("Playing")

print(student.hobbies) # prints >> ['Reading', 'Playing'] 
print(player.hobbies) # prints >> ['Reading', 'Playing']

Though they share the same base class, student and player are two separate instances of two separate classes. So I expected student.hobbies to return ['Reading'] and player.hobbies to return ['Playing'] after performing the append operation on each but that's clearly not the case. What am I not getting right?

1 Answers

This is because in your example hobbies is a class variable, not an instance variable. Use __init__ to declare it

class Person:
    def __init__(self):
        self.hobbies = []

print(student.hobbies)  # ['Reading']
print(player.hobbies)  # ['Playing']
Related