Python練習題 統計總共例項化了多少個物件

2021-09-29 23:45:57 字數 1875 閱讀 1725

需求:有乙個計數器(屬性),統計總共例項化了多少個物件

**如下:

class

student

: school =

'luffycity'

count =

0def

__init__

(self, name, age, ***)

: self.name = name

self.age = age

self.*** = ***

self.count +=

1def

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)

結果為:

011

1

從以上結果可以看出,如果寫成self.count ,他就會變成物件的私有屬性,所以說雖然例項化了3次,但是類的count值為0,每個物件的count值為1

從以下驗證**可以看出:

'''

'''print

(stu1.__dict__)

print

(stu2.__dict__)

print

(stu3.__dict__)

結果為

所以說正確的**例項如下:

class

student

: school =

'luffycity'

count =

0def

__init__

(self, name, age, ***)

: self.name = name

self.age = age

self.*** = ***

# self.count += 1

student.count +=

1def

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

結果為:33

33

python書中練習題 python練習題

1 定義乙個空列表,接收從鍵盤輸入的整數,把列表傳給乙個從大到小排序的函式,再輸出排序後的列表的值 listex b 0 a int input 請輸入列表長度 while b a num int input 請輸入字元 b 1 print listex sum 0 for i in range 0...

python的練習題 Python練習題

1 使用while迴圈輸入1 2 3 4 5 6 8 9 10 i 0while i 10 i i 1 if i 7 continue print i 結果 e python python python test.py1 2 求1 100的所有數的和 i 0sum 0 while i 100 i 1...

python練習題5 6統計工齡

給定公司n名員工的工齡,要求按工齡增序輸出每個工齡段有多少員工。輸入格式 輸入首先給出正整數n 10 5 即員工總人數 隨後給出n個整數,即每個員工的工齡,範圍在 0,50 輸出格式 按工齡的遞增順序輸出每個工齡的員工個數,格式為 工齡 人數 每項佔一行。如果人數為0則不輸出該項。如下 usr bi...