我开始用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
构造函数。对于创建预定义大小的列表还是仅单独添加每个条目之间的区别,我尤其感到困惑。
答案 0 :(得分:1)
进行以下更改后,您将得到什么:
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