0

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?

joaocandre
  • 1,621
  • 4
  • 25
  • 42
  • Part of the problem is that the constructor of myObject creates size copies of a reference to a single instance of baseClass. – quamrana May 12 '19 at 13:11
  • See [this](https://stackoverflow.com/questions/29785084/changing-one-list-unexpectedly-changes-another-too) post. While lists are mutable, pointers may be to same object – Andrew Allen May 12 '19 at 13:14
  • You want `inheritance`, read [Python - Object Oriented](https://www.tutorialspoint.com/python/python_classes_objects.htm). – stovfl May 12 '19 at 15:43
  • @AndrewAllen I think that only covers my attempt to change the list after initial instantiation, as such I am still trying to find a way for the `__init__` method of `myClass` to populate the list with different copies of `baseClass`? – joaocandre May 12 '19 at 19:11

1 Answers1

1

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
quamrana
  • 37,849
  • 12
  • 53
  • 71