I am trying to learn oop concepts and i chose python. As far as I know self.count and employee.count both calls the class variable count and they both should have same value. However, for the following code, I see that self.count is 1 and employee.count is 0.
class employee:
count=0
def __init__(self,x):
self.x=x
self.count=self.count+1
print ("this method is executed")
print (self.count)
print (employee.count)
emp1=employee("John")
解决方案
If You want to count number of created Employee, You have to create method which will invoke to every objects at all (not individually).
To do that, create method and decorate her with @staticmethod. Notice that this method don't have self in parenthesies. Moreover create variable (here: count), which also invoke to every class object at all (without self. before).
Finally put our count variable inside __init__ method with += 1 equation (than every time when new Employee will be created __init__ will add +1 to our variable). But remember to add Employee. before count here, to count every single create Employee as a class population.
class Employee(object):
count = 0
@staticmethod
def status():
print(Employee.count)
def __init__(self, x):
self.x = x
Employee.count += 1
print("this method is executed")
print("Now, we have got", Employee.count, "Employees")
emp1 = Employee("John")
We can show up population number with :
print(emp1.count)
emp1.status()
print(Employee.count)