Q:

Usage of Class Variables in Python

I trying to learn python classes and I was trying to learn how class variables works. When I execute the below code I see this error. I am just trying to understand why python is complaining about the Name "Employee". When I move the statement to Employee.employeecount = Employee.employeecount + 1 inside __init__ method I see its not complaining. Can someone please help me understand what exactly is happening.
Non-working Code:
class Employee(object):

    employeecount = 0
    Employee.employeecount = Employee.employeecount + 1

    def __init__(self,name,salary):
        self.name = name
        self.salary = salary

    def getdata(self):
        self.salary += 1
        print "Employee name: %s \nEmployee Salary: %d" % (self.name,self.salary)

    def getname(self):
        return self.name

    def getsalary(self):
        return self.salary

emp1 = Employee('Pradeep',8000)
emp1.getdata()

emp2 = Employee('Maddy',9000)
emp2.getdata()

print "Employee Count is %d" % Employee.employeecount
print "Employee Count is %d" % Employee.employeecount

name = emp1.getname()
salary = emp1.getsalary()

print "Name is %s and salary is %d" % (name,salary)

python classes.py 
Traceback (most recent call last):
  File "classes.py", line 4, in <module>
    class Employee(object):
  File "classes.py", line 6, in Employee
    Employee.employeecount = Employee.employeecount + 1
NameError: name 'Employee' is not defined

A:

The problem is that you're using the Employee.employeecount = Employee.employeecount + 1 line right in the class definition; that's going to be executed the instant your program starts, not when a new Employee is created.
At that point in time, the Employee class is going to see Employee.employeecount and try to look for some already-made Employee class - it's not going to realize that you want it to refer to itself. At that point in time, Employee has not been properly defined, because you're in the middle of defining it. On the other hand, if you place it inside the __init__ function, you see there's no problem - because by the time you are actually creating an Employee, the class has been properly defined.
What you would do instead at that point is just employeecount = employeecount + 1. That will get rid of the error, but that's probably not what you want to do. If you want to add to the count each time a new employee is created, put that Employee.employeecount = Employee.employeecount + 1 line in your __init__ function as you were doing. That should do the trick.

