python實例化對象的具體方法
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()
實例擴(kuò)展:
實例化過程:
class luffy_stu:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def eat(self):
pass
if __name__=="__main__":
stu1 = luffy_stu('bao',21,'male')
#實例化過程:
#1. 是先產(chǎn)生一個stu1對象,
#2. luffy_stu.__init__('stu1','bao',21,'male')再將stu1對象傳入__init__構(gòu)造函數(shù)中實例化對象
以上就是python實例化對象的具體方法的詳細(xì)內(nèi)容,更多關(guān)于python如何實例化對象的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
pyinstaller將python程序打包為可執(zhí)行文件
這篇文章主要介紹了pyinstaller將python程序打包為可執(zhí)行文件,pyinstaller是一個python打包工具,它將python程序及所需依賴都打包成一個可執(zhí)行文件2022-08-08
Python爬蟲之Selenium中frame/iframe表單嵌套頁面
這篇文章主要介紹了Python爬蟲之Selenium中frame/iframe表單嵌套頁面,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
pytorch保存和加載模型的方法及如何load部分參數(shù)
本文總結(jié)了pytorch中保存和加載模型的方法,以及在保存的模型文件與新定義的模型的參數(shù)不一一對應(yīng)時,我們該如何加載模型參數(shù),對pytorch保存和加載模型相關(guān)知識感興趣的朋友一起看看吧2024-03-03
Python圖像處理之直線和曲線的擬合與繪制【curve_fit()應(yīng)用】
這篇文章主要介紹了Python圖像處理之直線和曲線的擬合與繪制,結(jié)合實例形式分析了Python曲線擬合相關(guān)函數(shù)curve_fit()的使用技巧,需要的朋友可以參考下2018-12-12

