understanding output of class in python -


i beginner in programming , have started working on python.i running following code.please explain me sequence flow output

class employee:    empcount = 0     def __init__(self, name, salary):       self.name = name       self.salary = salary       self.empcount += 1     def displayemployee(self):       print "name : ", self.name,  ", salary: ", self.salary  emp1 = employee("abc", 2000) emp2 = employee("def", 5000)  print "total emp   : %d" % employee.empcount print "total emp1 : %d" % emp1.empcount print "total emp2: %d" % emp2.empcount 

and following output:

total emp  : 0 total emp1 : 1 total emp2: 1 

you using augmented assignment. immutable type integer, doing the same thing this:

  self.empcount = self.empcount + 1 

the self.empcount retrieves either instance attribute (if exists) or class attribute. because there no such instance attribute, class attribute (set 0) retrieved , 1 assigned self.empcount. assignment instance attribute always sets instance attribute, never class attribute. each of instances ends self.empcount set 1 , class attribute never changes.

note if empcount mutable type, such list, assignment give instance attribute anyway, if augmented assignment also mutated class attribute. see why += behave unexpectedly on lists? augmented assignment on non-existing instance attributes idea., because augmented assignment this:

self.empcount = self.empcount.__iadd__(1) 

note explicit assignment self.empcount attribute.

if wanted increment class attribute, need explicitly:

employee.empcount += 1 

Comments