python中variable,python中self.variable名称和classname.variable之间的区别

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值