前言
本文主要講述了python類中的三類常用方法,普通方法、類方法和靜態方法。
本文主要參考了https://youtu.be/rq8cL2XMM5M,強烈推薦一看這個系列的所有視頻。
運行環境
1
2
|
import sys sys.version |
結果為
'3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]'
普通方法
我們這里定義一個叫做學生的類,并在其中定義了一個普通方法total_score()用于獲取某個實例的學生的總分。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Student( object ): num_of_stu = 0 #學生人數 def __init__( self , name, age, math, Chinese): self .name = name #學生姓名 self .age = age #學生年齡 self .math = math #數學成績 self .Chinese = Chinese #語文成績 Student.num_of_stu + = 1 #每實例化一個學生,人數加1,相當于靜態變量 def __del__( self ): Student.num_of_stu - = 1 #每刪除一個實例,人數減1 #普通方法,用于計算學生的總分 def total_score( self ): return self .math + self .Chinese |
然后我們生成幾個實例試一下看
1
2
3
4
5
6
7
8
|
print (Student.num_of_stu) stu1 = Student( 'Bob' , 11 , 51 , 33 ) print (stu1.total_score()) stu2 = Student( 'Peco' , 12 , 98 , 79 ) print (stu2.total_score()) print (Student.num_of_stu) del stu1 print (Student.num_of_stu) |
結果為
0
84
177
2
1
類方法
現在假設我們想用一個字符串來實現實現一個實例的實例化,那么我們可以加上一個類方法from_string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Student( object ): num_of_stu = 0 #學生人數 def __init__( self , name, age, math, Chinese): self .name = name #學生姓名 self .age = age #學生年齡 self .math = math #數學成績 self .Chinese = Chinese #語文成績 Student.num_of_stu + = 1 #每實例化一個學生,人數加1,相當于靜態變量 def __del__( self ): Student.num_of_stu - = 1 #每刪除一個實例,人數減1 #普通方法,用于計算學生的總分 def total_score( self ): return self .math + self .Chinese #類方法,用于用字符串生成實例 @classmethod def from_string( cls , stu_str): name, age, math, Chinese = stu_str.split( '-' ) return cls (name, int (age), float (math), float (Chinese)) |
我們來試一下看
1
2
3
|
stu_str = "Bob-12-50-34" stu1 = Student.from_string(stu_str) print (stu1.name, stu1.total_score()) |
結果是
Bob 84.0
靜態方法
現在又假設我們需要類中有一個方法可以幫我們看看是不是上課日,那么我們就需要靜態方法了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
class Student( object ): num_of_stu = 0 #學生人數 def __init__( self , name, age, math, Chinese): self .name = name #學生姓名 self .age = age #學生年齡 self .math = math #數學成績 self .Chinese = Chinese #語文成績 Student.num_of_stu + = 1 #每實例化一個學生,人數加1,相當于靜態變量 def __del__( self ): Student.num_of_stu - = 1 #每刪除一個實例,人數減1 #普通方法,用于計算學生的總分 def total_score( self ): return self .math + self .Chinese #類方法,用于用字符串生成實例 @classmethod def from_string( cls , stu_str): name, age, math, Chinese = stu_str.split( '-' ) return cls (name, int (age), float (math), float (Chinese)) #靜態方法,用于判斷要不要上學 @staticmethod def is_school_day(day): if day.weekday() = = 5 or day.weekday() = = 6 : return False return True |
我們來試下看
1
2
3
4
5
|
import datetime my_date1 = datetime.date( 2017 , 9 , 15 ) my_date2 = datetime.date( 2017 , 9 , 16 ) print (Student.is_school_day(my_date1)) print (Student.is_school_day(my_date2)) |
結果是
True
False
以上就是python編程普通及類和靜態方法示例詳解的詳細內容,更多關于python方法的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/zjuPeco/article/details/78006661