Python3:如何创建同一个类的不同对象的dict?

时间:2013-02-22 08:40:58

标签: python python-3.x

我想创建一个包含同一类的几个对象的dict。每个对象必须是独立的。 类似的东西:

#!/usr/bin/python3

class myReserve():

    myList = dict()

    def __init__(self, initName):
        self.myName = initName
        self.setList()

    def setList(self):
        if self.myName == "fruit":
            self.myList[0] = "Orange"
            self.myList[1] = "Lemon"
        elif self.myName == "vegetable":
            self.myList[0] = "Tomato"
            self.myList[1] = "Carrot"
        #If neither fruit nor vegetable
        #myList should be empty.


myStore = dict()
myStore[0] = myReserve("fruit")
myStore[1] = myReserve("vegetable")
myStore[2] = myReserve("spices")

print(myStore[0].myList)

打印:

{0: 'Tomato', 1: 'Carrot'}

我以为会打印出来:

{0: 'Orange', 1: 'Lemon'}

我理解对象在Python中通过引用传递。

dict1 = {"var": 128}
dict2 = dict1
dict2["var"] = 0
print(dict1["var"])

将打印:

0

通过创建一个类,我想为不同的对象创建一个结构。我不明白第一个代码示例的行为。是否有可能以Python的方式做这样的事情?

1 个答案:

答案 0 :(得分:1)

您的问题是您在类级别定义myList,以便它由myReserve的每个实例共享。请尝试在myReserve.__init__中定义它:

class myReserve():
    def __init__(self, initName):
        self.myList = dict()

完整代码:

#!/usr/bin/python3

class myReserve():
    def __init__(self, initName):
        self.myList = dict()
        self.myName = initName
        self.setList()

    def setList(self):
        if self.myName == "fruit":
            self.myList[0] = "Orange"
            self.myList[1] = "Lemon"
        elif self.myName == "vegetable":
            self.myList[0] = "Tomato"
            self.myList[1] = "Carrot"
        #If neither fruit nor vegetable
        #myList should be empty.


myStore = dict()
myStore[0] = myReserve("fruit")
myStore[1] = myReserve("vegetable")
myStore[2] = myReserve("spices")

print(myStore[0].myList)