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}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM