0

Sorry if the question isn't that clear in the title but I had a limited amount of space, To clarify...

In my code I have a class called empDB that creates an empty list for storing objects.

Too add new objects to the list I created a method in empDB called appendEmp. appendEmp takes one parameter that specifies the class which it will instantiate and then add it to the list. If no parameter is provided it defaults to the class Employee().

here is my problem

when I call the method appendEmp it creates new objects in the list, however when I try to instantiate an object thats already in the list it will only create an alias of it. I need it to create a new one each time so that i can edit the attributes of each object in the list individually.

here is a snippet of my code:

class empDB:

    def __init__(self, lst= []):                  #creates empty list
        self.lst = lst

    def appendEmp(self, emp=Employee()):
        self.lst=self.lst+[emp]

basicly this is what happens now

>>> db=empDB()
>>> db.appendEmp()
>>> db.appendEmp()
>>> db[0] is db[1]
True

I need it to be false

Jeff LaFay
  • 12,882
  • 13
  • 71
  • 101
The Room
  • 3
  • 1

2 Answers2

1

You can solve your problem like that:

class empDB:
    def __init__(self, lst= []):  #creates empty list
        self.lst = lst
    def appendEmp(self, emp=None):
        if emp is None:
            empt = Employee()
        self.lst=self.lst+[emp]

The issue was caused by mutable value being assigned as the default argument. I replaced it with None, although if you would like to accept this value as the argument of appendEmp(), you can replace it with something else.

More on dangers of using mutable default arguments you can read here: Hidden features of Python: Dangers of mutable default arguments

Ps. You may also wish to do the same for __init__() method.

Community
  • 1
  • 1
Tadeck
  • 132,510
  • 28
  • 152
  • 198
0

A mutable default argument can cause trouble if you aren't fully aware of how they work. Most beginners don't realize that the default value for a keyword argument is computed exactly once, when the definition is processed. If the function code modifies this object thereafter then the next call to use the default object will see the modified value.

I explain this with pictures starting at http://holdenweb.com/files/IntroNotes.pdf#page=118

These notes, by the way, are the draft of an open source release of my "Introduction to Python" class, so I'd appreciate any feedback.

holdenweb
  • 33,305
  • 7
  • 57
  • 77