Python中的特殊方法以及應(yīng)用詳解
前言
Python 中的特殊方法主要是為了被解釋器調(diào)用的,因此應(yīng)該盡量使用 len(my_object) 而不是 my_object.__len__() 這種寫法。在執(zhí)行 len(my_object) 時(shí),Python 解釋器會(huì)自行調(diào)用 my_object 中實(shí)現(xiàn)的 __len__ 方法。
除非有大量的元編程存在,直接調(diào)用特殊方法的頻率應(yīng)遠(yuǎn)小于實(shí)現(xiàn)它們的次數(shù)。
模擬數(shù)值類型
可以通過在自定義對(duì)象中實(shí)現(xiàn) __add__ 和 __mul__ 等特殊方法 ,令其支持 +、* 等運(yùn)算符。
如下面的模擬向量的 Vector 類:
# vector.py from math import hypot class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y def __repr__(self): return f'Vector({self.x}, {self.y})' def __abs__(self): return hypot(self.x, self.y) def __bool__(self): return bool(self.x or self.y) def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __mul__(self, scalar): return Vector(self.x * scalar, self.y * scalar)
運(yùn)行效果如下:
>>> from vector import Vector
>>> v1 = Vector(2, 4)
>>> v2 = Vector(2, 1)
>>> v1 + v2
Vector(4, 5)
>>> v = Vector(3, 4)
>>> abs(v)
5.0
>>> v * 3
Vector(9, 12)
對(duì)象的字符串表示
Python 有一個(gè) repr 內(nèi)置函數(shù),能把一個(gè)對(duì)象用字符串的形式表示出來。實(shí)際上這種字符串表達(dá)是通過對(duì)象內(nèi)部的 __repr__ 特殊方法定義的。默認(rèn)情況下,在控制臺(tái)里查看某個(gè)對(duì)象時(shí),輸出的字符串一般是 <xxx object at 0x7fc99d6ab2e0> 這種形式。
__repr__ 返回的字符串應(yīng)該準(zhǔn)確、無歧義,并盡可能表示出該對(duì)象是如何創(chuàng)建的。比如前面的 Vector 對(duì)象,其 __repr__ 中定義的字符串形式類似于 Vector(3, 4),和對(duì)象初始化的語法非常近似。
__repr__ 和 __str__ 的區(qū)別在于,__str__ 是在向?qū)ο髴?yīng)用 str() 函數(shù)(或者用 print 函數(shù)打印某個(gè)對(duì)象)時(shí)被調(diào)用。其返回的字符串對(duì)終端用戶更友好。
如果只想實(shí)現(xiàn)其中一個(gè)特殊方法,__repr__ 應(yīng)該是更優(yōu)的選擇。在對(duì)象沒有實(shí)現(xiàn) __str__ 方法的情況下,Python 解釋器會(huì)用 __repr__ 代替。
# myclass.py class MyClass: def __repr__(self): return 'MyClass' def __str__(self): return 'This is an instance of MyClass'
>>> from myclass import MyClass >>> my = MyClass() >>> my MyClass >>> print(my) This is an instance of MyClass
自定義布爾值
Python 里有 bool 類型,但實(shí)際上任何對(duì)象都可以用在需要 bool 類型的上下文(比如 if 或 while 語句)中。為了判斷某個(gè)值 x 的真假,Python 會(huì)調(diào)用 bool(x) 返回 True 或 False。
默認(rèn)情況下,自定義類的實(shí)例總是為真。除非這個(gè)類對(duì)于 __bool__ 或 __len__ 方法有自己的實(shí)現(xiàn)。
bool(x) 實(shí)際上調(diào)用了對(duì)象 x 中的 __bool__ 方法。如不存在 __bool__ 方法,則 bool(x) 會(huì)嘗試調(diào)用 x.__len__(),返回 0 則為 False,否則為 True。
# boolclass.py class BoolClass: def __init__(self): self.list = [] def add(self, item): self.list.append(item) def __len__(self): return len(self.list)
>>> from boolclass import BoolClass >>> b = BoolClass() >>> len(b) 0 >>> bool(b) False >>> b.add(1) >>> len(b) 1 >>> bool(b) True
# boolclass.py class BoolClass: def __init__(self): self.list = [] def add(self, item): self.list.append(item) def __len__(self): return len(self.list) def __bool__(self): return bool(sum(self.list))
>>> from boolclass import BoolClass >>> b = BoolClass() >>> b.add(1) >>> len(b) 1 >>> bool(b) True >>> b.add(-1) >>> len(b) 2 >>> bool(b) False
參考資料
總結(jié)
到此這篇關(guān)于Python中特殊方法以及應(yīng)用詳解的文章就介紹到這了,更多相關(guān)Python特殊方法及應(yīng)用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
win10環(huán)境下python3.5安裝步驟圖文教程
本文通過圖文并茂的形式給大家介紹了win10環(huán)境下python3.5安裝步驟,需要的朋友可以參考下2017-02-02python添加列表元素append(),extend()及?insert()
這篇文章主要介紹了python添加列表元素append(),extend()及?insert(),列表是儲(chǔ)存元素的數(shù)據(jù)類型,既然能存儲(chǔ)元素,那么就類似數(shù)據(jù)庫一樣,增刪改查的一些功能就不能少了。下面我們就來先看看添加列表元素方法有哪些,需要的朋友可以參考一下2022-03-03Python裝飾器實(shí)現(xiàn)函數(shù)運(yùn)行時(shí)間的計(jì)算
這篇文章主要為大家詳細(xì)介紹了Python函數(shù)運(yùn)行時(shí)間的計(jì)算,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02