0

我想创建一个字典,其中包含同一类的多个对象。每个对象必须是独立的。就像是:

#!/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 的方式做这样的事情?

4

1 回答 1

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)
于 2013-02-22T09:15:45.903 回答