Python中類的創(chuàng)建和實例化操作示例
本文實例講述了Python中類的創(chuàng)建和實例化操作。分享給大家供大家參考,具體如下:
python中同樣使用關(guān)鍵字class創(chuàng)建一個類,類名稱第一個字母大寫,可以帶括號也可以不帶括號;
python中實例化類不需要使用關(guān)鍵字new(也沒有這個關(guān)鍵字),類的實例化類似函數(shù)調(diào)用方式;
# coding: utf-8
# 創(chuàng)建一個類,類名稱第一個字母大寫,可以帶括號也可以不帶括號
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
# 創(chuàng)建類的對象(實例化類)
# python中實例化類不需要使用關(guān)鍵字new(也沒有這個關(guān)鍵字),類的實例化類似函數(shù)調(diào)用方式。
student1 = Student('cuiyongyuan',10)
student2 = Student('yuanli', 10)
student1.display_student()
student2.display_student()
student1_class = student1.get_class()
student2_class = student2.get_class()
運行結(jié)果:
Name: cuiyongyuan, age: 10
Name: yuanli, age: 10
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python Pandas中創(chuàng)建Series的三種方法總結(jié)
這篇文章主要介紹了Python Pandas中創(chuàng)建Series的三種方法總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
詳解python中靜態(tài)方法staticmethod用法
本文主要介紹了python中靜態(tài)方法staticmethod用法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
如何通過python代碼根據(jù)模板修改變量生成新yaml文件
有些時候,需要根據(jù)一個yaml模板創(chuàng)建多個yaml文件實例,我們先寫一個yaml文件模板,然后通過python代碼修改模板中的變量,存儲為一個新的yaml文件,需要配合python的庫Template及ymal使用,本文給大家講解的非常詳細(xì),需要的朋友跟隨小編一起看看吧2023-11-11

