python的普通方法、类方法和静态方法
生活随笔
收集整理的這篇文章主要介紹了
python的普通方法、类方法和静态方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
本文主要講述了python類中的三類常用方法,普通方法、類方法和靜態方法。
普通方法會將實例傳入方法當中(通常用self表示),類方法會將類傳入方法當中(通常用cls表示),靜態方法中傳入與類無關的變量。下面將舉例詳細說明。
本文主要參考了https://youtu.be/rq8cL2XMM5M,強烈推薦一看這個系列的所有視頻。
運行環境
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()用于獲取某個實例的學生的總分。
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然后我們生成幾個實例試一下看
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
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#類方法,用于用字符串生成實例@classmethoddef from_string(cls, stu_str):name, age, math, Chinese = stu_str.split('-')return cls(name, int(age), float(math), float(Chinese))我們來試一下看
stu_str = "Bob-12-50-34" stu1 = Student.from_string(stu_str) print (stu1.name, stu1.total_score())結果是
Bob 84.0靜態方法
現在又假設我們需要類中有一個方法可以幫我們看看是不是上課日,那么我們就需要靜態方法了
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#類方法,用于用字符串生成實例@classmethoddef from_string(cls, stu_str):name, age, math, Chinese = stu_str.split('-')return cls(name, int(age), float(math), float(Chinese))#靜態方法,用于判斷要不要上學@staticmethoddef is_school_day(day):if day.weekday() == 5 or day.weekday() == 6:return Falsereturn True我們來試下看
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的普通方法、类方法和静态方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我们并没有觉得MapReduce速度慢,
- 下一篇: LeetCode 1824. 最少侧跳次