I'm starting to develop some code in python (have some experience with C and C++) and I'm having trouble understanding how to pass a particular type to the constructor of another class. Considering the example:

class baseClass(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

class myClass(object):
    def __init__(self, otherClass,size):
        self.myMember = [otherClass] * size 

    def addMemberInstance(self,otherClass):
        self.myMember.append(otherClass)

    def setOtherClassX(self,pos,x):
        self.myMember[pos].x = x

    def getOtherClassX(self,pos):
        return self.myMember[pos].x

    def printMemberXs(self):
        print("----")
        for m in self.myMember:
            print(m.x)
        print("----")

# populate myClass myMember list with 10 instances of baseClass
foo = myClass(baseClass(5,6),10)  
foo.printMemberXs()

# change atribute of myMember entry at pos 3 with val 16
foo.setOtherClassX(3,16)
foo.printMemberXs() # apparently all entries in the list are changed

# append a new entry to myMember with a new instance of baseClass
foo.addMemberInstance(baseClass(3,7))
foo.printMemberXs()

# change atribute of new myMember entry (at pos 10) with val 47
foo.setOtherClassX(10,47)
foo.printMemberXs() #only the last entry was changed!

The reason I'm attempting this is that I will have several classes that will be derived from baseClass, and would like to pass the type/constructor/instance to the myClass constructor. I am particularly confused as to the difference between creating a list of predefined size or just appending each entry individually?

1 Answers

1
quamrana On

To get what you are after make these changes:

class myClass(object):
    def __init__(self, instances):  # parameter of a list of separate instances
        self.myMember = instances
    # rest of members

foo = myClass([baseClass(5,6) for _ in range(10)])  # Make a list with 10 distinct instances
# rest of program here