我正在尝试创建一个类的多个实例,该实例正在另一个类的多个实例中使用,如下代码所示。在
我只想在python中使用'nodeInfo'类作为数据类型来存储初始化它的任何实例的不同值,这样就可以很容易地在由另一个类“Build”形成的其他实例中使用。在
但是,在代码中,变量“a”和“b”的“test1”、“test2”和“test3”的实例共享nodeInfo类的相同值。在
你能帮我用一个类nodeInfo作为唯一的数据类型吗?所以我可以存储不同的值?在
我希望我的问题是清楚的。非常感谢您的帮助。在class nodeInfo(object):
itemValues = {
"attributes" : [],
"values" : []
}
def __init__(self, attributes, values):
print "calling constructor of nodeInfo Class"
self.itemValues["attributes"] = attributes
self.itemValues["values"] = values
class Build(object):
v = ''
a = nodeInfo
b = nodeInfo
def __init__(self, name):
a = nodeInfo([1,2,3], [1,2,3])
b = nodeInfo([1,2,3], [1,2,3])
v = name
def setItem(self, attribute, value):
self.a = nodeInfo(attribute, value)
test = Build("a")
test2 = Build("b")
test3 = Build("c")
print test.a.itemValues, test2.a.itemValues, test3.a.itemValues
#test.setItem([3,2,1], [3,2,1])
#test2.a.itemValues = nodeInfo([3,2,1], [3,2,1])
test3.setItem([3,2,1], [3,2,1])
print test.a.itemValues, test2.a.itemValues, test3.a.itemValues
结果:
^{pr2}$
应该是:calling constructor of nodeInfo Class
{'attributes': [1, 2, 3], 'values': [1, 2, 3]} {'attributes': [1, 2, 3], 'values': [1, 2, 3]} {'attributes': [1, 2, 3], 'values': [1, 2, 3]}
calling constructor of nodeInfo Class
{'attributes': [1, 2, 3], 'values': [1, 2, 3]} {'attributes': [1, 2, 3], 'values': [1, 2, 3]} {'attributes': [3, 2, 1], 'values': [3, 2, 1]}