python - 将类型/类实例作为参数传递给类构造函数?
问题描述
我开始在 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
构造函数。我对创建预定义大小列表或仅单独附加每个条目之间的区别感到特别困惑?
解决方案
要获得您所做的更改后的内容:
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
推荐阅读
- objective-c - 如何在 NSNotification 中心嵌入一个 Objective-C 枚举?
- spring - org.jboss.as.ejb3.component.EJBComponentUnavailableException: WFLYEJB0467: 请求被拒绝,因为容器被挂起
- c - 互斥体应该存储在 main 中还是对象中?
- css - 在 yaml 标头中指定的自定义背景图像
- c# - 限制 Observable GroupBy / Merge 组合的并发性
- c# - 模拟多个接口实例:最后一个模拟的设置会影响其他模拟
- c# - Response.AddHeader 附件文件和 AntiForgeryToken()
- linux - devshell环境和bitbake任务环境的区别?
- tfs - TFS 2018 - 无法在版本中使用 Environment.Name
- json - 我需要在后续 json 数据上设置什么连接表达式?