0

I would like to create a dict, containing several objects of the same class. Each object must be independent. Something like:

#!/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)

This prints:

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

I thought it would print:

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

I understood objects are passed by reference in Python.

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

Will print:

0

By creating a class I want to create a structure for different objects. I don't understand the behaviour of the first code example. Is it possible to do something like this in a Python way?

1 Answer 1

1

Your problem is that you're defining myList on the class level, so that it's shared by every instance of myReserve. Try defining it in myReserve.__init__ instead:

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

Full code:

#!/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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.