-1

I am a beginner in programming and have started working on Python.I am running following code.Please explain me the sequence flow for the 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 I get following output:

Total Emp  : 0
Total Emp1 : 1
Total Emp2: 1
Fermi
  • 115
  • 1
  • 6
  • What *precisely* don't you understand? The one thing that might trip you up is that `self.empCount += 1` is assigning to an *instance attribute*, using and then shadowing the *class attribute* of the same name, which is why the last line doesn't show `2`. – jonrsharpe Jul 15 '15 at 10:32

2 Answers2

1

You are using augmented assignment. For an immutable type like an integer, you are essentially doing the same thing as this:

  self.empCount = self.empCount + 1

The self.empCount retrieves either an instance attribute (if it exists) or a class attribute. Because there is no such instance attribute, it is the class attribute (set to 0) that is retrieved and 1 is assigned to self.empCount. Assignment to an instance attribute always sets an instance attribute, never the class attribute. Each of your instances thus ends up with self.empCount set to 1 and the class attribute never changes.

Note that even if empCount was a mutable type, such as a list, the assignment would give you an instance attribute anyway, even if the augmented assignment also mutated the class attribute. See Why does += behave unexpectedly on lists? Augmented assignment on non-existing instance attributes is rarely a good idea., because the augmented assignment does this:

self.empCount = self.empCount.__iadd__(1)

Note the explicit assignment to the self.empCount attribute.

If you wanted to increment the class attribute, you need to do so explicitly:

Employee.empCount += 1
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-1
class Employee:
   empCount = 0

by here, Total Emp, which just show Employee.empCount remains 0.

 def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      self.empCount += 1

this inherits and defines the Employee, and adds self.empcount. Which as a result, adds 1 to empCount.

emp1 = Employee("ABC", 2000)
emp2 = Employee("DEF", 5000)

emp1 and emp2 is separate object and affected by init individually, which makes empCount 1.

jooShin
  • 140
  • 1
  • 14