如何在其他类中创建一个类的多个实例(新实例)?

2024-10-01 13:33:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个类的多个实例,该实例正在另一个类的多个实例中使用,如下代码所示。在

我只想在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]}

Tags: of实例testbuildselfdefattributesvalues
2条回答

当您在NodeInfo.__init__之外声明itemValues时,您正在创建一个类属性,该属性将由所有NodeInfo实例共享。在

如果您希望NodeInfo.itemValues是一个实例属性,并且每个实例都有唯一的(对象),则需要在__init__方法中创建。在

class NodeInfo(object):
    def __init__(self, attributes, values):
        # print "calling constructor of NodeInfo Class"
        self.itemValues = dict()
        self.itemValues["attributes"] = attributes
        self.itemValues["values"] = values
    def __str__(self):
        return str(self.itemValues)

要给实例属性赋值,需要使用self.attribute = ...。您在Build.__init__中缺少这个。在

^{pr2}$

用法:

>>> test = Build('a')
>>> test2 = Build('b')
>>> print '{}:{}    -   {}:{}'.format(test.v, test.a, test2.v, test2.a)
a:{'attributes': [1, 2, 3], 'values': [1, 2, 3]}    -   b:{'attributes': [1, 2, 3], 'values': [1, 2, 3]}
>>>
>>> test2.setItem(['x', 'y', 'z'], ['c', 'b', 'a'])
>>>
>>> print '{}:{}    -   {}:{}'.format(test.v, test.a, test2.v, test2.a)
a:{'attributes': [1, 2, 3], 'values': [1, 2, 3]}    -   b:{'attributes': ['x', 'y', 'z'], 'values': ['c', 'b', 'a']}
>>>

看看Python Tutorial - 9. Classes。当你到了9.3的结尾,你会发现一个类似的例子。建议您阅读整个章节,9、9.1和9.2是Python的重要概念。在

从a和b的生成中删除声明

当您像这样声明类成员时,它们被视为静态成员,并在所有类实例中共享

然后构造函数必须将a和b作为self.a和self.b引用,否则它们将被视为局部变量

编辑:

class Build(object):

    def __init__(self, name):
        self.a = nodeInfo([1,2,3], [1,2,3])
        self.b = nodeInfo([1,2,3], [1,2,3])
        self.v = name

    def setItem(self, attribute, value):
        self.a = nodeInfo(attribute, value)

    def getItemA(self):
        return self.a

    def getItemB(self):
        return 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}$

相关问题 更多 >