Python练习--统计总共实例化了多少个对象

需求:有一个计数器(属性),统计总共实例化了多少个对象

代码如下:

 1 class Student:
 2     school = 'Luffycity'
 3     count = 0
 4 
 5     def __init__(self, name, age, sex):
 6         self.name = name
 7         self.age = age
 8         self.sex = sex
 9         self.count += 1
10 
11     def learn(self):
12         print('%s is learning' % self.name)
13 
14 stu1 = Student('alex', 'male', 38)
15 stu2 = Student('jinxin', 'female', 78)
16 stu3 = Student('Egon', 'male', 18)
17 
18 print(Student.count)
19 print(stu1.count)
20 print(stu2.count)
21 print(stu3.count)

结果为:

0
1
1
1

从以上结果可以看出,如果写成self.count ,他就会变成对象的私有属性,所以说虽然实例化了3次,但是类的count值为0,每个对象的count值为1

从以下验证代码可以看出:

1 print(stu1.__dict__)
2 print(stu2.__dict__)
3 print(stu3.__dict__)
4 
5 结果为
6 
7 {'name': 'alex', 'age': 'male', 'sex': 38, 'count': 1}
8 {'name': 'jinxin', 'age': 'female', 'sex': 78, 'count': 1}
9 {'name': 'Egon', 'age': 'male', 'sex': 18, 'count': 1}

所以说正确的代码实例如下:

 1 class Student:
 2     school = 'Luffycity'
 3     count = 0
 4 
 5     def __init__(self, name, age, sex):
 6         self.name = name
 7         self.age = age
 8         self.sex = sex
 9         # self.count += 1
10         Student.count += 1
11 
12     def learn(self):
13         print('%s is learning' % self.name)
14 
15 stu1 = Student('alex', 'male', 38)
16 stu2 = Student('jinxin', 'female', 78)
17 stu3 = Student('Egon', 'male', 18)
18 
19 print(Student.count)
20 print(stu1.count)
21 print(stu2.count)
22 print(stu3.count)
23 print(stu1.__dict__)
24 print(stu2.__dict__)
25 print(stu3.__dict__)
26 
27 结果为:
28 
29 3
30 3
31 3
32 3
33 {'name': 'alex', 'age': 'male', 'sex': 38}
34 {'name': 'jinxin', 'age': 'female', 'sex': 78}
35 {'name': 'Egon', 'age': 'male', 'sex': 18}