python編程普通及類和靜態(tài)方法示例詳解
本文主要講述了python類中的三類常用方法,普通方法、類方法和靜態(tài)方法。
本文主要參考了https://youtu.be/rq8cL2XMM5M,強烈推薦一看這個系列的所有視頻。
運行環(huán)境
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 #學生人數(shù) def __init__(self, name, age, math, Chinese): self.name = name #學生姓名 self.age = age #學生年齡 self.math = math #數(shù)學成績 self.Chinese = Chinese #語文成績 Student.num_of_stu += 1 #每實例化一個學生,人數(shù)加1,相當于靜態(tài)變量 def __del__(self): Student.num_of_stu -= 1 #每刪除一個實例,人數(shù)減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
類方法
現(xiàn)在假設我們想用一個字符串來實現(xiàn)實現(xiàn)一個實例的實例化,那么我們可以加上一個類方法from_string
class Student(object): num_of_stu = 0 #學生人數(shù) def __init__(self, name, age, math, Chinese): self.name = name #學生姓名 self.age = age #學生年齡 self.math = math #數(shù)學成績 self.Chinese = Chinese #語文成績 Student.num_of_stu += 1 #每實例化一個學生,人數(shù)加1,相當于靜態(tài)變量 def __del__(self): Student.num_of_stu -= 1 #每刪除一個實例,人數(shù)減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))
我們來試一下看
stu_str = "Bob-12-50-34" stu1 = Student.from_string(stu_str) print (stu1.name, stu1.total_score())
結果是
Bob 84.0
靜態(tài)方法
現(xiàn)在又假設我們需要類中有一個方法可以幫我們看看是不是上課日,那么我們就需要靜態(tài)方法了
class Student(object): num_of_stu = 0 #學生人數(shù) def __init__(self, name, age, math, Chinese): self.name = name #學生姓名 self.age = age #學生年齡 self.math = math #數(shù)學成績 self.Chinese = Chinese #語文成績 Student.num_of_stu += 1 #每實例化一個學生,人數(shù)加1,相當于靜態(tài)變量 def __del__(self): Student.num_of_stu -= 1 #每刪除一個實例,人數(shù)減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)) #靜態(tài)方法,用于判斷要不要上學 @staticmethod def is_school_day(day): if day.weekday() == 5 or day.weekday() == 6: return False return 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編程普通及類和靜態(tài)方法示例詳解的詳細內容,更多關于python方法的資料請關注本站其它相關文章!
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。