python中self.variable名称和classname.variable之间的区别 [英] Difference between self.variable name and classname.variable in python

查看:169
本文介绍了python中self.variable名称和classname.variable之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习oop概念,因此我选择了python.据我所知self.count和employee.count都调用类变量count并且它们都应具有相同的值.但是,对于以下代码,我看到self.count为1,而employee.count为0.

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")       

推荐答案

如果要计算已创建的Employee的数量,则必须创建一种方法,该方法将调用所有对象(而不是单独调用).

If You want to count number of created Employee, You have to create method which will invoke to every objects at all (not individually).

为此,请创建方法并用@staticmethod装饰她.请注意,此方法的括号中没有self.此外,创建变量(此处为count),该变量也将完全调用每个类对象(之前没有self.).

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).

最后将我们的count变量与+= 1公式放在__init__方法内(比每次创建新的Employee的时间__init__都将+1加到我们的变量中).但是请记住,在此处在count之前添加Employee.,以将每个创建的Employee都算作一个类人口.

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")

我们可以使用:

print(emp1.count)
emp1.status()
print(Employee.count)

这篇关于python中self.variable名称和classname.variable之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆