Python基礎(chǔ)-特殊方法整理詳解
1、概述
python中特殊方法(魔術(shù)方法)是被python解釋器調(diào)用的,我們自己不需要調(diào)用它們,我們統(tǒng)一使用內(nèi)置函數(shù)來使用。例如:特殊方法__len__()實(shí)現(xiàn)后,我們只需使用len()方法即可;也有一些特殊方法的調(diào)用是隱式的,例如:for i in x: 背后其實(shí)用的是內(nèi)置函數(shù)iter(x)。
下面將介紹一些常用特殊方法和實(shí)現(xiàn)。通過實(shí)現(xiàn)一個(gè)類來說明
2、常用特殊方法及實(shí)現(xiàn)
2.1 _len__()
一般返回?cái)?shù)量,使用len()方法調(diào)用。在__len__()內(nèi)部也可使用len()函數(shù)
class Zarten():
def __init__(self, age):
self.age = age
self.brother = ['zarten_1', 'zarten_2']
def __len__(self):
return len(self.brother) #可直接使用len()
# return self.age
z = Zarten(18)
print(len(z))
2.2 __str__()
對(duì)象的字符串表現(xiàn)形式,與__repr__()基本一樣,微小差別在于:
__str__()用于給終端用戶看的,而__repr__()用于給開發(fā)者看的,用于調(diào)試和記錄日志等。- 在命令行下,實(shí)現(xiàn)
__str_()后,直接輸入對(duì)象名稱會(huì)顯示對(duì)象內(nèi)存地址;而實(shí)現(xiàn)__repr__()后,跟print(對(duì)象)效果一樣。 - 若這2個(gè)都實(shí)現(xiàn),會(huì)調(diào)用
__str_(),一般在類中至少實(shí)現(xiàn)__repr__()

class Zarten():
def __repr__(self):
return 'my name is Zarten_1'
def __str__(self):
return 'my name is Zarten_2'
z = Zarten()
print(z)
2.3 __iter__()
返回一個(gè)可迭代對(duì)象,一般跟__next__()一起使用
判斷一個(gè)對(duì)象是否是:可迭代對(duì)象 from collections import Iterable
from collections import Iterable
class Zarten():
def __init__(self, brother_num):
self.brother_num = brother_num
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count >= self.brother_num:
raise StopIteration
else:
self.count += 1
return 'zarten_' + str(self.count)
zarten = Zarten(5)
print('is iterable:', isinstance(zarten, Iterable)) #判斷是否為可迭代對(duì)象
for i in zarten:
print(i)
2.4 __getitem__()
此特殊方法返回?cái)?shù)據(jù),也可以替代__iter_()和__next__()方法,也可支持切片
class Zarten():
def __init__(self):
self.brother = ['zarten_1','zarten_2','zarten_3','zarten_4','zarten_5',]
def __getitem__(self, item):
return self.brother[item]
zarten = Zarten()
print(zarten[2])
print(zarten[1:3])
for i in zarten:
print(i)
2.5 __new__()
__new__()用來構(gòu)造一個(gè)類的實(shí)例,第一個(gè)參數(shù)是cls,一般情況下不會(huì)使用。而__init__()用來初始化實(shí)例,所以__new__()比__init___()先執(zhí)行。
若__new__()不返回,則不會(huì)有任何對(duì)象創(chuàng)建,__init___()也不會(huì)執(zhí)行;
若__new__()返回別的類的實(shí)例,則__init___()也不會(huì)執(zhí)行;
用途:可使用__new___()實(shí)現(xiàn)單例模式
class Zarten():
def __new__(cls, *args, **kwargs):
print('__new__')
return super().__new__(cls)
def __init__(self, name, age):
print('__init__')
self.name = name
self.age = age
def __repr__(self):
return 'name: %s age:%d' % (self.name,self.age)
zarten = Zarten('zarten', 18)
print(zarten)

2.6 使用__new__()實(shí)現(xiàn)單例模式
class Zarten():
_singleton = None
def __new__(cls, *args, **kwargs):
print('__new__')
if not cls._singleton:
cls._singleton = super().__new__(cls)
return cls._singleton
def __init__(self, name, age):
print('__init__')
self.name = name
self.age = age
def __repr__(self):
return 'name: %s age:%d' % (self.name,self.age)
zarten = Zarten('zarten', 18)
zarten_1 = Zarten('zarten_1', 19)
print(zarten)
print(zarten_1)
print(zarten_1 == zarten)

2.7 __call__()
實(shí)現(xiàn)后對(duì)象可變成可調(diào)用對(duì)象,此對(duì)象可以像函數(shù)一樣調(diào)用,例如:自定義函數(shù),內(nèi)置函數(shù),類都是可調(diào)用對(duì)象,可用callable()判斷是否是可調(diào)用對(duì)象
class Zarten():
def __init__(self, name, age):
self.name = name
self.age = age
def __call__(self):
print('name:%s age:%d' % (self.name, self.age))
z = Zarten('zarten', 18)
print(callable(z))
z()
2.8__enter__()
一個(gè)上下文管理器的類,必須要實(shí)現(xiàn)這2個(gè)特殊方法:__enter_()和__exit__() 使用with語(yǔ)句來調(diào)用。
使用__enter__()返回對(duì)象,使用__exit__()關(guān)閉對(duì)象
class Zarten():
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, exc_type, exc_val, exc_tb):
self.file_obj.close()
print('closed')
with Zarten('e:\\test.txt', 'r') as f:
r = f.read()
print(r)
2.9 __add__()
加法運(yùn)算符重載以及__radd__()反向運(yùn)算符重載
當(dāng)對(duì)象作加法時(shí),首先會(huì)在“+”左邊對(duì)象查找__add__(),若沒找到則在“+”右邊查找__radd__()
class Zarten():
def __init__(self, age):
self.age = age
def __add__(self, other):
return self.age + other
def __radd__(self, other):
return self.age + other
z = Zarten(18)
print(z + 10)
print(20 + z)
2.10 __del__()
對(duì)象生命周期結(jié)束時(shí)調(diào)用,相當(dāng)于析構(gòu)函數(shù)
class Zarten():
def __init__(self, age):
self.age = age
def __del__(self):
print('__del__')
z = Zarten(18)
特殊(魔術(shù))方法匯總一覽表

到此這篇關(guān)于Python基礎(chǔ)-特殊方法詳解的文章就介紹到這了,更多相關(guān)Python基礎(chǔ)-特殊方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 用turtle實(shí)現(xiàn)用正方形畫圓的例子
今天小編就為大家分享一篇Python 用turtle實(shí)現(xiàn)用正方形畫圓的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Python+pyftpdlib實(shí)現(xiàn)局域網(wǎng)文件互傳
這篇文章主要介紹了Python+pyftpdlib實(shí)現(xiàn)局域網(wǎng)文件互傳,需要的朋友可以參考下2020-08-08
Python使用post及get方式提交數(shù)據(jù)的實(shí)例
今天小編就為大家分享一篇關(guān)于Python使用post及get方式提交數(shù)據(jù)的實(shí)例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
基于Python實(shí)現(xiàn)多圖繪制系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的多圖繪制系統(tǒng),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02
PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程)
這篇文章主要介紹了PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Python基礎(chǔ)之文件操作及光標(biāo)移動(dòng)詳解
這篇文章主要為大家介紹了Python基礎(chǔ)之文件操作及光標(biāo)移動(dòng)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11

