Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

inner classes of python loop referencing the same memory and assigning the last referenced variable

So im learning python and am trying to build a python file with inner classes and im trying to populate subjects as an array inside a class. However, it seems to be pointing to the same memory even though i am using a dictionary to ensure it does not happen. Is there any way for me to fix this issue?

I am trying to assign 2 subjects to my student. However, when accessing the name of the subjects, it is returning me the same subject which is located at the 1st index.

I’m used to java where i can just create a new instance of a class using the new tag.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Student:
    class Subject:
        def __init__(self):
            self.name = ''

    def __init__(self):
        self.name = ''
        self.subject = self.Subject()
        self.courses = {}


def test():
    courses = ['Subject A', 'Subject B']
    student = Student()
    student.name = 'apple'
    for i, course in enumerate(courses):
        student.courses[i] = student.Subject
        student.courses[i].name = course

    print(student.courses[0].name)
    print(student.courses[1].name)


test()

Thank you very much for the help! I am struggling to get a grasp of this.

>Solution :

The class is an object itself, so when you run

        student.courses[i] = student.Subject

you are not creating an instance of the class, you are setting the "static" class.

When you override the name here, you are doing it for the shared class.

student.courses[i].name = course

A fix would be:

        student.courses[i] = student.Subject()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading