詳細(xì)介紹python類及類的用法
一、類的成員
類的成員包括:屬性和方法。
屬性可以分為:靜態(tài)屬性和實(shí)例屬性
方法可以分為:普通方法、類方法和靜態(tài)方法。
1.1 類的屬性
屬性可以分為:靜態(tài)屬性和實(shí)例屬性。
實(shí)例屬性屬于對(duì)象,而靜態(tài)屬性屬于類。
通過類創(chuàng)建對(duì)象時(shí),如果每個(gè)對(duì)象都具有相同的屬性,那么就使用靜態(tài)屬性。
1.1.1 靜態(tài)屬性的創(chuàng)建方式
靜態(tài)屬性是屬于類的,所以不用創(chuàng)建對(duì)象訪問。
class Province: # 靜態(tài)字段 country = '中國' # 直接訪問靜態(tài)字段 Province.country
例如:
1.1.2 實(shí)例屬性
lass Goods: def __init__(self): # 原價(jià) self.original_price = 100 # 折扣 self.discount = 0.8 @property def price(self): # 實(shí)際價(jià)格 = 原價(jià) * 折扣 new_price = self.original_price * self.discount return new_price @price.setter def price(self, value): self.original_price = value @price.deleter def price(self): del self.original_price
例如:
實(shí)例屬性可以在構(gòu)造方法中進(jìn)行初始化。@property裝飾器可以把一個(gè)實(shí)例方法變成其同名屬性,以支持.號(hào)訪問。我們可以根據(jù)屬性的訪問特點(diǎn),分別將三個(gè)方法定義為對(duì)同一個(gè)屬性:獲取、修改、刪除。
擴(kuò)展:
對(duì)于靜態(tài)屬性還可以使用property函數(shù)的形式定義一個(gè)屬性。與@property實(shí)現(xiàn)原理類似。
property(fget=None, fset=None, fdel=None, doc=None)
class Foo: def get_bar(self): return 'get_bar' # *必須兩個(gè)參數(shù) def set_bar(self, value): return 'set value' + value def del_bar(self): return 'del_bar' age = property(fget=get_bar,fset=set_bar,fdel=del_bar,doc='description...')
例如:
1.2 類的方法
方法包括:普通方法、類方法和靜態(tài)方法。
普通方法:由對(duì)象調(diào)用;至少一個(gè)self參數(shù);執(zhí)行普通方法時(shí),自動(dòng)將調(diào)用該方法的對(duì)象賦值給self;
類方法:由類調(diào)用; 至少一個(gè)cls參數(shù);執(zhí)行類方法時(shí),自動(dòng)將調(diào)用該方法的類復(fù)制給cls;
靜態(tài)方法:由類調(diào)用;無默認(rèn)參數(shù);
class Foo: def __init__(self, name): self.name = name def ord_func(self): """ 定義普通方法,至少有一個(gè)self參數(shù) """ # print self.name print('普通方法') @classmethod def class_func(cls): """ 定義類方法,至少有一個(gè)cls參數(shù) """ print('類方法') @staticmethod def static_func(): """ 定義靜態(tài)方法 ,無默認(rèn)參數(shù)""" print('靜態(tài)方法')
例如:
如果Python中沒有屬性,方法完全可以代替其功能。
二、類成員的修飾符
對(duì)于每一個(gè)類的成員而言都有兩種形式:
公有成員,在任何地方都能訪問。
私有成員,只有在類的內(nèi)部才能方法。
私有成員和公有成員的定義不同:私有成員命名時(shí),前兩個(gè)字符是下劃線。(特殊成員除外,例如:__init__、__call__、__dict__等)
ps:如果想要強(qiáng)制訪問私有字段,可以通過 【對(duì)象._類名__私有字段明 】訪問(如:obj._C__foo),不建議強(qiáng)制訪問私有成員。
class C: name = '公有靜態(tài)字段' __sname ='私有靜態(tài)字段' def pub_func(self): print(C.name) def pra_func(self): print(C._sname) class D(C): def pub_show(self): print(C.name) def pra_show(self): print(C._sname)
例如:
注:不建議強(qiáng)制訪問私有成員。
三、類的特殊成員
3.1 __doc__
表示類的描述信息。
>>> class Foo: """ 描述類信息,這是用于看片的神奇 """ def func(self): pass >>> Foo.__doc__ ' 描述類信息,這是用于看片的神奇
3.2 __module__ 和 __class__
__module__ 表示當(dāng)前操作的對(duì)象在哪個(gè)模塊
__class__ 表示當(dāng)前操作的對(duì)象的類是什么
>>> class Foo: """ 描述類信息,這是用于看片的神奇 """ def func(self): pass >>> obj = Foo() >>> obj.__module__ '__main__' >>> obj.__class__ <class '__main__.Foo'>
3.3 __init__
構(gòu)造方法,通過類創(chuàng)建對(duì)象時(shí),自動(dòng)觸發(fā)執(zhí)行。
>>> class Foo: def __init__(self, name): self.name = name self.age = 18 >>> obj = Foo('test') >>> obj.name 'test'
3.4 __del__
當(dāng)對(duì)象在內(nèi)存中被釋放時(shí),自動(dòng)觸發(fā)執(zhí)行。
3.5 __call__
對(duì)象后面加括號(hào),觸發(fā)執(zhí)行。
>>> class Foo: def __init__(self): pass def __call__(self, *args, **kwargs): print('__call__') >>> obj = Foo() >>> obj() __call__
3.6 __dict__
類或?qū)ο笾械乃谐蓡T。
>>> class Province: country = 'China' def __init__(self, name, count): self.name = name self.count = count def func(self, *args, **kwargs): print('func') >>> print(Province.__dict__) # 獲取類的成員,即:靜態(tài)字段、方法 {'__module__': '__main__', 'country': 'China', '__init__': <function Province.__init__ at 0x0000000002F39820>, 'func': <function Province.func at 0x0000000002F398B0>, '__dict__': <attribute '__dict__' of 'Province' objects>, '__weakref__': <attribute '__weakref__' of 'Province' objects>, '__doc__': None} >>> obj1 = Province('jiangxi',10000) >>> print(obj1.__dict__) #獲取 對(duì)象obj1 的成員 {'name': 'jiangxi', 'count': 10000}
3.7 __str__
如果一個(gè)類中定義了__str__方法,那么在打印 對(duì)象 時(shí),默認(rèn)輸出該方法的返回值。有點(diǎn)像java中的toString方法。
>>> class Foo: def __str__(self): return 'test' >>> obj = Foo() >>> print(obj) test
3.8 __getitem__、__setitem__、__delitem__
用于索引操作,如字典。以上分別表示獲取、設(shè)置、刪除數(shù)據(jù)。
3.9 __getslice__、__setslice__、__delslice__
三個(gè)方法用于分片操作。
3.10 __iter__
用于迭代器,之所以列表、字典、元組可以進(jìn)行for循環(huán),是因?yàn)轭愋蛢?nèi)部定義了 __iter__。
>>> class Foo(object): def __init__(self, sq): self.sq = sq def __iter__(self): return iter(self.sq) >>> for i in obj: print(i) 11 22 33 44 >>>
到此這篇關(guān)于詳細(xì)介紹python類的使用的文章就介紹到這了,更多相關(guān)python類的使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python drf各類組件的用法和作用
- python定義類的簡單用法
- python db類用法說明
- Python面向?qū)ο蟪绦蛟O(shè)計(jì)之靜態(tài)方法、類方法、屬性方法原理與用法分析
- Python面向?qū)ο蟪绦蛟O(shè)計(jì)之類和對(duì)象、實(shí)例變量、類變量用法分析
- python編程進(jìn)階之類和對(duì)象用法實(shí)例分析
- Python面向?qū)ο笾蓄悾╟lass)的簡單理解與用法分析
- Python3變量與基本數(shù)據(jù)類型用法實(shí)例分析
- Python 面向?qū)ο笾恈lass和對(duì)象基本用法示例
- python定義類self用法實(shí)例解析
- Python中類似于jquery的pyquery庫用法分析
- Python上下文管理器類和上下文管理器裝飾器contextmanager用法實(shí)例分析
相關(guān)文章
NumPy實(shí)現(xiàn)從已有的數(shù)組創(chuàng)建數(shù)組
本文介紹了NumPy中如何從已有的數(shù)組創(chuàng)建數(shù)組,包括使用numpy.asarray,numpy.frombuffer和numpy.fromiter方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-10-10python中常用的數(shù)據(jù)結(jié)構(gòu)介紹
這篇文章主要介紹了python中常用的數(shù)據(jù)結(jié)構(gòu)介紹,幫助大家更好的理解和學(xué)習(xí)python的基礎(chǔ)知識(shí),感興趣的朋友可以了解下2021-01-01將數(shù)據(jù)集制作成VOC數(shù)據(jù)集格式的實(shí)例
今天小編就為大家分享一篇將數(shù)據(jù)集制作成VOC數(shù)據(jù)集格式的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python Selenium網(wǎng)頁自動(dòng)化利器使用詳解
這篇文章主要為大家介紹了使用Python Selenium實(shí)現(xiàn)網(wǎng)頁自動(dòng)化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12一款強(qiáng)大的端到端測試工具Playwright介紹
這篇文章主要為大家介紹了一款強(qiáng)大的端到端測試工具Playwright介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01python+os根據(jù)文件名自動(dòng)生成文本
這篇文章主要為大家詳細(xì)介紹了python+os根據(jù)文件名自動(dòng)生成文本,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-03-03Python中多線程thread與threading的實(shí)現(xiàn)方法
這篇文章主要介紹了Python中多線程thread與threading的實(shí)現(xiàn)方法,很重要的應(yīng)用,需要的朋友可以參考下2014-08-08