0

I am learning Python and usually do really easy personal tasks too keep in my mind all this new language. The thing is, that I am having an issue that I don't really know what is wrong and maybe soomeone can explain. I am a noob in all this, so maybe for sou it is so easy to see my problem, but I've been breaking my brain for a while and I cannot understand what is wrong.

The thing is that I am receiving duplicated values on the terminal from a list when I .instert or .append them.

The code it's quite simple:

class Student:
    def __init__(self, name, surname, age):
        Student.name = name
        Student.surname = surname
        Student.age = age
        Student.subjects = [] # Atributo no obligatorio en forma de LIST.

student001 = Student("Mary", "Stone", 17)
student002 = Student("James", "Lincoln", 16)


student001.subjects.append("English")
student002.subjects.append("English")

print(student001.subjects)
print(student002.subjects)

student001.subjects.append("P.E.")
student002.subjects.insert(1, "P.E.")

print(student001.subjects)
print(student002.subjects)

The problem is when I print it and I receive duplicated values on the terminal:

['English', 'English']
['English', 'English']
['English', 'P.E.', 'English', 'P.E.']
['English', 'P.E.', 'English', 'P.E.']

May anyone explain me what I am doing wrong?

Thanks in advence! :)

I want to receive this:

['English']
['English']
['English', 'P.E.']
['English', 'P.E.']
2
  • 1
    More importantly, you should notice that every instance has the name and age of the last instance defined. Commented Feb 13, 2023 at 17:29
  • Welcome to Stack Overflow. In your own words, where the code saysStudent.name = name, exactly what do you think this means? Specifically, what do you think the Student. part will do? Commented Feb 13, 2023 at 18:05

1 Answer 1

0

You are defining class attributes (shared by all instances) rather than instance attributes unique to each instance. Replace Student with self:

class Student:
    def __init__(self, name, surname, age):
        self.name = name
        self.surname = surname
        self.age = age
        self.subjects = [] # Atributo no obligatorio en forma de LIST.
Sign up to request clarification or add additional context in comments.

1 Comment

Lol! True! I just get stupid on that! This is what happens when you don't sleep enough. Thank you so much, pal!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.