本文實例講述了Python中類的創建和實例化操作。分享給大家供大家參考,具體如下:
python中同樣使用關鍵字class創建一個類,類名稱第一個字母大寫,可以帶括號也可以不帶括號;
python中實例化類不需要使用關鍵字new(也沒有這個關鍵字),類的實例化類似函數調用方式;
# coding: utf-8# 創建一個類,類名稱第一個字母大寫,可以帶括號也可以不帶括號class Student(): student_count = 0 def __init__(self, name, salary):  self.name = name  self.age = salary  Student.student_count += 1 def display_count(self):  print('Total student {}'.format(Student.student_count)) def display_student(self):  print('Name: {}, age: {}'.format(self.name,self.age)) def get_class(self):  if self.age >= 7 and self.age < 8:   return 1  if self.age >= 8 and self.age < 9:   return 2  if self.age >= 9 and self.age < 10:   return 3  if self.age >= 10 and self.age < 11:   return 4  else:   return 0# 創建類的對象(實例化類)# python中實例化類不需要使用關鍵字new(也沒有這個關鍵字),類的實例化類似函數調用方式。student1 = Student('cuiyongyuan',10)student2 = Student('yuanli', 10)student1.display_student()student2.display_student()student1_class = student1.get_class()student2_class = student2.get_class()運行結果:
Name: cuiyongyuan, age: 10
Name: yuanli, age: 10
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答