employees = []
for i in range(0,10):
emp = Employee(i)
emp.first_name = "%s-%s"%("first name", i)
emp.last_name = "%s-%s"%("last_name", i)
emp.desgination = "%s-%s"%("engineer", i)
employees.append(emp)
ids = [e.eid for e in employees]
Following is my class definition:
class Employee:
_fields = {}
def __init__(self, eid):
self.eid = eid
def __getattr__(self, name):
return self._fields.get(name)
def __setattr__(self,name,value):
self._fields[name] = value
def __str__(self):
return str(self._fields)
def __unicode__(self):
return str(self._fields)
The issue is that when I print ids, it contains 10 times 9… i.e.
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
It seems that the same emp variable is being overwritten. I am not sure what going wrong. Though I am a Java coder but I thought I had a fair idea of Python as well.
The problem is, indeed, your java past ! 🙂
The error is here:
_fieldsis a CLASS member ! So each instance of Employee shares the same_fieldsvar, and whenever you modify one, you modify all other objects.You must move the
_fields = {}part into the__init__function :But then, you will run into another problem:
self.eid = xxinvokes the__setattr__method! (and so does self._fields !)The solution is to use
self.__dict__['_fields']when you need to access to the instance’s ‘_fields’ member instead ofself._fields. It will directly access the member, instead of going through__getattr__and an infinite reccursion, with a nice stack overflow in the end.