首页 > 解决方案 > 将类型/类实例作为参数传递给类构造函数?

问题描述

我开始在 python 中开发一些代码(对 C 和 C++ 有一些经验),但我无法理解如何将特定类型传递给另一个类的构造函数。考虑这个例子:

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!

我尝试这样做的原因是我将有几个派生自 的类baseClass,并且希望将类型/构造函数/实例传递给myClass构造函数。我对创建预定义大小列表或仅单独附加每个条目之间的区别感到特别困惑?

标签: pythonlistclassobjectarguments

解决方案


要获得您所做的更改后的内容:

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

推荐阅读