我正在尝试创建一个类的多个实例,该实例正在另一个类的多个实例中使用,如下代码所示。在
我只想在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
结果:
应该是:
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]}
当您在
NodeInfo.__init__
之外声明itemValues
时,您正在创建一个类属性,该属性将由所有NodeInfo
实例共享。在如果您希望
NodeInfo.itemValues
是一个实例属性,并且每个实例都有唯一的值(对象),则需要在__init__
方法中创建。在要给实例属性赋值,需要使用
^{pr2}$self.attribute = ...
。您在Build.__init__
中缺少这个。在用法:
看看Python Tutorial - 9. Classes。当你到了9.3的结尾,你会发现一个类似的例子。建议您阅读整个章节,9、9.1和9.2是Python的重要概念。在
从a和b的生成中删除声明
当您像这样声明类成员时,它们被视为静态成员,并在所有类实例中共享
然后构造函数必须将a和b作为self.a和self.b引用,否则它们将被视为局部变量
编辑:
=====================================================
谢谢你。这是实际结果和代码,它认为相同的节点信息是静态的。我发现如果我不使用nodeInfo并用dict创建一个实例来构建。它不是用作静态的,但是在这种情况下,我们将丢失已经定义的数据类型。在
结果: {'attributes':[1,2,3],'values':[1,2,3]}{'attributes':[1,2,3],'values':[1,2,3],'values':[1,2,3]} 调用nodeInfo类的构造函数 {'attributes':[3,2,1],'values':[3,2,1]}{'attributes':[3,2,1],'values':[3,2,1],'values':[3,2,1]}
代码:
^{pr2}$相关问题 更多 >
编程相关推荐