赞
踩
需求:有一个计数器(属性),统计总共实例化了多少个对象
代码如下:
class Student: school = 'Luffycity' count = 0 def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex self.count += 1 def learn(self): print('%s is learning' % self.name) stu1 = Student('alex', 'male', 38) stu2 = Student('jinxin', 'female', 78) stu3 = Student('Egon', 'male', 18) print(Student.count) print(stu1.count) print(stu2.count) print(stu3.count)
结果为:
0
1
1
1
从以上结果可以看出,如果写成self.count ,他就会变成对象的私有属性,所以说虽然实例化了3次,但是类的count值为0,每个对象的count值为1
从以下验证代码可以看出:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
print(stu1.__dict__)
print(stu2.__dict__)
print(stu3.__dict__)
结果为
{'name': 'alex', 'age': 'male', 'sex': 38, 'count': 1}
{'name': 'jinxin', 'age': 'female', 'sex': 78, 'count': 1}
{'name': 'Egon', 'age': 'male', 'sex': 18, 'count': 1}
所以说正确的代码实例如下:
class Student: school = 'Luffycity' count = 0 def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex # self.count += 1 Student.count += 1 def learn(self): print('%s is learning' % self.name) stu1 = Student('alex', 'male', 38) stu2 = Student('jinxin', 'female', 78) stu3 = Student('Egon', 'male', 18) print(Student.count) print(stu1.count) print(stu2.count) print(stu3.count) print(stu1.__dict__) print(stu2.__dict__) print(stu3.__dict__) 结果为: 3 3 3 3 {'name': 'alex', 'age': 'male', 'sex': 38} {'name': 'jinxin', 'age': 'female', 'sex': 78} {'name': 'Egon', 'age': 'male', 'sex': 18}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。