Home > OS >  Passing an object to an object in a list of objects
Passing an object to an object in a list of objects

Time:10-01

I'm trying to create a list of objects (Called Super in this example) and pass an object to that object (Called Sub in this example).

However, whenever I do that, Python recognizes that each of the Super classes are individual objects, but the sub classes within are all the same. It looks like the one Sub object is the last one to be passed through and each one that gets passed through overwrites the previous.

The goal is that I would get the number back (0 - 4), but because they are all the same object, I just get the last one (4) back. What would be a solution or workaround?

driver.py

from Super import *
from Sub import *

class1 = []
class2 = []
for a in range(0,5):
    class1.append(Sub(a))

for a in range(0,5):
    class2.append(Super(class1[a]))


for a in range(0,5):
    class2[a].printnumber()

Super.py

class Super:
    def __init__(self, a):
        global class1
        class1 = a

    def printnumber(self):
        print(class1.getnumber())

Sub.py

class Sub:
    def __init__(self, a):
        global number
        number = a

    def getnumber(self):
        return number

CodePudding user response:

You may be confusing global variables with member variables. If each instance of a class should have its own copy of a variable, you should do it like this:

class Sub:
    def __init__(self, a):
        self.number = a

    def getnumber(self):
        return self.number

The self describes that you assign it to your object.

If you use global, the variable is shared over all instances. Generally you should avoid using global, since it is almost always possible to achieve the same thing in a significantly cleaner way!

  • Related