python?特殊屬性及方法詳細(xì)解析
概述
在python中,以單下劃線(xiàn)開(kāi)頭的(_a)的代表不能直接訪(fǎng)問(wèn)的類(lèi)屬性,需通過(guò)類(lèi)提供的接口進(jìn)行訪(fǎng)問(wèn),不能用“from xxx import *”而導(dǎo)入,“單下劃線(xiàn)” 開(kāi)始的成員變量叫做保護(hù)變量,意思是只有類(lèi)對(duì)象和子類(lèi)對(duì)象自己能訪(fǎng)問(wèn)到這些變量;以雙下劃線(xiàn)開(kāi)頭的(_ _a)代表類(lèi)的私有成員,意思是只有類(lèi)對(duì)象自己能訪(fǎng)問(wèn),連子類(lèi)對(duì)象也不能訪(fǎng)問(wèn)到這個(gè)數(shù)據(jù);以雙下劃線(xiàn)開(kāi)頭和結(jié)尾的(_ _a_ _)代表python里特殊方法專(zhuān)用的標(biāo)識(shí),如 _ _init_ _()代表類(lèi)的構(gòu)造函數(shù)。
特殊屬性
1、 _ _ name _ _
如果是一個(gè)對(duì)象的調(diào)用,則表示類(lèi)的名稱(chēng),而不是表示對(duì)象的名稱(chēng);如果當(dāng)前模塊被直接執(zhí)行(主模塊),_ _ name _ _ 存儲(chǔ)的是_ _ main _ _ ;如果當(dāng)前模塊是被調(diào)用的模塊(被導(dǎo)入),則_ _ name _ _存儲(chǔ)的是py文件名(模塊名稱(chēng))。
1、表示對(duì)象的名稱(chēng)
>>> class A(object): a = 1 def __init__(self): self.b = 'c' >>> a = A() >>> A.__name__ 'A' >>> a.__name__ Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> a.__name__ AttributeError: 'A' object has no attribute '__name__'
2、表示_ _ main _ _函數(shù)的名稱(chēng),也就是程序的入口,類(lèi)似于java中main函數(shù)
>>> __name__ '__main__'
3、如果當(dāng)前模塊被其他模塊調(diào)用,則是當(dāng)前模塊的名稱(chēng)
demo1.py
print(__name__)
demo2.py
import demo1
運(yùn)行demo2.py文件后,得到的結(jié)果為:
demo1
2、_ _ bases _ _ 和_ _ base _ _ 以及 _ _ mro _ _
_ _ bases _ _ 表示類(lèi)的所有基類(lèi);_ _ base _ _ 輸出類(lèi)繼承的第一個(gè)父類(lèi)(類(lèi)的基類(lèi)); _ _ mro _ _ 輸出類(lèi)的層次結(jié)構(gòu)。
>>> class A: def __init__(self): self.a = 2 >>> class B(A): def __init__(self): super().__init__() self.b = 3 >>> class C(A): def __init__(self): super().__init__() self.c = 4 >>> class D(B, C): def __init__(self): super().__init__() self.d = 5 >>> D.__bases__ (<class '__main__.B'>, <class '__main__.C'>) >>> D.__base__ <class '__main__.B'> >>> D.__mro__ (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
3、_ _ class _ _
表示對(duì)象的類(lèi)型,相當(dāng)于type()函數(shù)。
>>> class A: def __init__(self): self.a = 2 >>> a = A() >>> a.__class__ <class '__main__.A'>
4、_ _ dict _ _
表示對(duì)象和類(lèi)的一些屬性,用一個(gè)字典存儲(chǔ)起來(lái)。
>>> class A: a = 1 b = 2 def __init__(self): self.c = 3 self.d = 4 >>> a = A() >>> a.__dict__ {'c': 3, 'd': 4} >>> A.__dict__ mappingproxy({'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function A.__init__ at 0x000001CD66F6B8B0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
特殊方法
1、 _ _ subclasses _ _ ()
表示類(lèi)的所有直接子類(lèi)。
>>> class A: def __init__(self): self.a = 2 >>> class B(A): def __init__(self): super().__init__() self.b = 3 >>> class C(A): def __init__(self): super().__init__() self.c = 4 >>> class D(B, C): def __init__(self): super().__init__() self.d = 5 >>> C.__subclasses__() [<class '__main__.D'>] >>> A.__subclasses__() [<class '__main__.B'>, <class '__main__.C'>]
2、_ _ new _ _ ()、 _ _ init _ _ ()和 _ _ del _ _ ()
_ _ new _ _ ()是一個(gè)靜態(tài)方法,用于根據(jù)類(lèi)型創(chuàng)建實(shí)例。Python在調(diào)用 _ _ new _ _ ()方法獲得實(shí)例后,會(huì)調(diào)用這個(gè)實(shí)例的_ _ init _ _ ()方法,然后將最初傳給 _ _ new _ _ ()方法的參數(shù)都傳給 _ _ init _ _ ()方法。
_ _ init _ _ ()是一個(gè)實(shí)例方法,用來(lái)在實(shí)例創(chuàng)建完成后進(jìn)行必要的初始化,該方法必須返回None。Python不會(huì)自動(dòng)調(diào)用父類(lèi)的 _ _ init _ _ ()方法,這需要額外的調(diào)用:
super(C, self). _ _ init _ _ ()
_ _ new _ _ ()至少要有一個(gè)參數(shù)cls,代表要實(shí)例化的類(lèi),此參數(shù)在實(shí)例化時(shí)由Python解釋器自動(dòng)提供;_ _ new _ _ ()必須要有返回值,返回實(shí)例化出來(lái)的實(shí)例,可以return父類(lèi)new出來(lái)的實(shí)例,或直接是object的new出來(lái)的實(shí)例。
>>> class A(object): def __new__(cls, *args, **kwargs): print("__new__") instance = object.__new__(cls) # 或者 # instance = super().__new__(cls) return instance def __init__(self): print("__init__") >>> a = A() __new__ __init__
在GC之前,Python會(huì)調(diào)用這個(gè)對(duì)象的 _ _ del _ _ ()方法完成一些終止化工作。如果沒(méi)有 _ _ del _ _ ()方法,那么Python不做特殊的處理;此外,Python無(wú)視_ _ del _ _ ()方法的返回值;Python不會(huì)自動(dòng)調(diào)用父類(lèi)的 _ _ del _ _ ()方法,除非顯式調(diào)用;定義了 _ _ del _ _ ()方法的實(shí)例無(wú)法參與到循環(huán)GC中,所以對(duì)于這樣的實(shí)例應(yīng)該避免循環(huán)引用;try/finally語(yǔ)句或with語(yǔ)句可能是比_ _ del _ _()更好的方式。
>>> class A(object): def __new__(cls, *args, **kwargs): print("__new__") instance = super().__new__(cls, *args, **kwargs) return instance def __init__(self): print("__init__") def __del__(self): print("__del__") >>> a = A() __new__ __init__ >>> del a __del__
3、_ _ repr _ _ ()和 _ _ str _ _ ()
_ _ repr _ _ ()是一個(gè) ”自我描述“ 的方法,也是Python類(lèi)中的一個(gè)特殊方法,由object對(duì)象提供,由于object提供的這個(gè) _ _ repr _ _ 方法總是返回一個(gè)對(duì)象, ( 類(lèi)名 + obejct at + 內(nèi)存地址 ),這個(gè)值并不能真正實(shí)現(xiàn)自我描述的功能,如果你想在自定義類(lèi)中實(shí)現(xiàn) “自我描述” 的功能,那么必須重寫(xiě) _ _ repr _ _ 方法。_ _ repr _ _ ()方法返回的字符串主要是面向解釋器的。
>>> class A(object): def __repr__(self): return "this is a class A" >>> a = A() >>> a this is a class A >>> print(a) this is a class A >>> str(a) 'this is a class A'
_ _ str _ _ ()與_ _ repr _ _ ()返回的詳盡的、準(zhǔn)確的、無(wú)歧義的對(duì)象描述字符串不同,_ _ str _ _ ()方法只是返回一個(gè)對(duì)應(yīng)對(duì)象的簡(jiǎn)潔的字符串表達(dá)形式。如上代碼所示,當(dāng)_ _ str _ _ ()缺失時(shí),Python會(huì)調(diào)用_ _ repr _ _ ()方法。
>>> class A(object): def __str__(self): return "this is a class A" >>> a = A() >>> a <__main__.A object at 0x000001CF8C8F9640> >>> print(a) this is a class A >>> str(a) 'this is a class A'
實(shí)際上_ _ str _ _ ()只是覆蓋了_ _ repr _ _ ()以得到更友好的用戶(hù)顯示。Python內(nèi)置的str()函數(shù),print(x)語(yǔ)句,都會(huì)調(diào)用對(duì)象的_ _ str _ _()方法。
>>> class A(object): def __repr__(self): return "class A" def __str__(self): return "this is a class A" >>> a = A() >>> a class A >>> print(a) this is a class A >>> str(a) 'this is a class A'
4、_ _ call _ _ ()
定義了該方法的對(duì)象可以像函數(shù)那樣被調(diào)用,因此被稱(chēng)為可調(diào)用對(duì)象。
>>> class A(object): def __init__(self): self.a = 2 def __call__(self, b, *args, **kwargs): c = b + self.a return c >>> a = A() >>> a(3) 5
5、_ _ lt _ _ ()、_ _ le _ _ ()、_ _ gt _ _ ()、_ _ ge _ _ ()、_ _ eq _ _ ()、_ _ ne _ _ ()
當(dāng)兩個(gè)對(duì)象x、y分別進(jìn)行x<y、x<=y、x>y、x>=y、x==y和x!=y運(yùn)算時(shí),會(huì)調(diào)用對(duì)應(yīng)的函數(shù)。
>>> class A(object): def __init__(self, b): self.b = b def __lt__(self, other): print("__lt__") return self.b < other.b >>> c = A(3) >>> d = A(4) >>> c < d __lt__ True
6、_ _ hash _ _ ()
三種情形會(huì)調(diào)用__hash__()方法:1. 內(nèi)置的hash()方法,2.作為字典的鍵時(shí),3.作為集合的成員時(shí);_ _ hash _ _ ()方法應(yīng)該返回一個(gè)32位長(zhǎng)的整數(shù),對(duì)與同一個(gè)對(duì)象,hash()方法應(yīng)該總是返回相同的值;對(duì)于 x == y ,即使二者不屬于相同的類(lèi)型,只要他們是可哈希的(hashable),都應(yīng)該確保得到 hash(x) == hash(y) ;
>>> class A(object): def __init__(self, n): self.n = n def __eq__(self, other): return self.n == other.n def __hash__(self): return random.randint(0, 10) >>> a = A(3) >>> b = A(3) >>> a == b True # 雖然a == b返回結(jié)果為T(mén)rue,但是hash(a)和hash(b)返回結(jié)果不一樣,所以不能說(shuō)這兩個(gè)對(duì)象是相同的。 >>> hash(a) 3 >>> hash(b) 5
_ _ eq _ _()正確的用法:
class A(object): def __init__(self, n): self.n = n def __hash__(self): return hash(id(self)) def __eq__(self, other): if isinstance(other, self.__class__): return hash(id(self))==hash(id(other)) else: return False
通過(guò)_ _ hash _ _ 返回一個(gè)int值,用來(lái)標(biāo)記這個(gè)對(duì)象。對(duì)于類(lèi)而言,如果沒(méi)有實(shí)現(xiàn)_ _ eq _ _ ()和 _ _ hash _ _ ()函數(shù),那么會(huì)自動(dòng)繼承object._ _ hash _ _()。
到此這篇關(guān)于python 特殊屬性及方法詳細(xì)解析的文章就介紹到這了,更多相關(guān)python 屬性方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python?遠(yuǎn)程執(zhí)行命令的詳細(xì)代碼
有時(shí)會(huì)需要在遠(yuǎn)程的機(jī)器上執(zhí)行一個(gè)命令,并獲得其返回結(jié)果。對(duì)于這種情況,python 可以很容易的實(shí)現(xiàn)。今天通過(guò)實(shí)例代碼介紹下python?遠(yuǎn)程執(zhí)行命令的相關(guān)知識(shí),感興趣的朋友一起看看吧2022-02-02Python的Flask框架中使用Flask-SQLAlchemy管理數(shù)據(jù)庫(kù)的教程
在Python中我們可以使用SQLAlchemy框架進(jìn)行數(shù)據(jù)庫(kù)操作,那么對(duì)應(yīng)的在Flask框架中我們可以使用SQLAlchemy,下面我們就來(lái)看一下Python的Flask框架中使用Flask-SQLAlchemy管理數(shù)據(jù)庫(kù)的教程2016-06-06對(duì)PyQt5中樹(shù)結(jié)構(gòu)的實(shí)現(xiàn)方法詳解
今天小編就為大家分享一篇對(duì)PyQt5中樹(shù)結(jié)構(gòu)的實(shí)現(xiàn)方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06Python模糊查詢(xún)本地文件夾去除文件后綴的實(shí)例(7行代碼)
下面小編就為大家?guī)?lái)一篇Python模糊查詢(xún)本地文件夾去除文件后綴的實(shí)例(7行代碼) 。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11Python利用GDAL模塊實(shí)現(xiàn)讀取柵格數(shù)據(jù)并對(duì)指定數(shù)據(jù)加以篩選掩膜
這篇文章主要為大家詳細(xì)介紹了如何基于Python語(yǔ)言中g(shù)dal模塊,對(duì)遙感影像數(shù)據(jù)進(jìn)行柵格讀取與計(jì)算,同時(shí)基于QA波段對(duì)像元加以篩選、掩膜的操作,需要的可以參考一下2023-02-02淺談keras2 predict和fit_generator的坑
這篇文章主要介紹了淺談keras2 predict和fit_generator的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06