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
You can solve your problem like that:
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 ofappendEmp(), 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.