Python運算子多載的代碼教程

來源:互聯網
上載者:User
這篇文章主要介紹了Python運算子多載詳解及執行個體代碼的相關資料,需要的朋友可以參考下

Python運算子多載

Python語言提供了運算子多載功能,增強了語言的靈活性,這一點與C++有點類似又有些不同。鑒於它的特殊性,今天就來討論一下Python運算子多載。

Python語言本身提供了很多魔法方法,它的運算子多載就是通過重寫這些Python內建魔法方法實現的。這些魔法方法都是以雙底線開頭和結尾的,類似於X的形式,python通過這種特殊的命名方式來攔截操作符,以實現重載。當Python的內建操作運用於類對象時,Python會去搜尋並調用對象中指定的方法完成操作。

類可以重載加減運算、列印、函數調用、索引等內建運算,運算子多載使我們的對象的行為與內建對象的一樣。Python在叫用作業符時會自動調用這樣的方法,例如,如果類實現了add方法,當類的對象出現在+運算子中時會調用這個方法。

常見運算子多載方法

方法名

重載說明

運算子調用方式

init

建構函式

對象建立: X = Class(args)

del

解構函式

X對象收回

add/sub

加減運算

X+Y, X+=Y/X-Y, X-=Y

or

運算子|

X|Y, X|=Y

_repr/str

列印/轉換

print(X)、repr(X)/str(X)

call

函數調用

X(*args, **kwargs)

getattr

屬性引用

X.undefined

setattr

屬性賦值

X.any=value

delattr

屬性刪除

del X.any

getattribute

屬性擷取

X.any

getitem

索引運算

X[key],X[i:j]

setitem

索引賦值

X[key],X[i:j]=sequence

delitem

索引和分區刪除

del X[key],del X[i:j]

len

長度

len(X)

bool

布爾測試

bool(X)

lt, gt,

le, ge,

eq, ne

特定的比較

依次為X<Y,X>Y,X<=Y,X>=Y,

X==Y,X!=Y

注釋:(lt: less than, gt: greater than,

le: less equal, ge: greater equal,

eq: equal, ne: not equal

)

radd

右側加法

other+X

iadd

實地(增強)加法

X+=Y(or else add)

iter, next

迭代

I=iter(X), next()

contains

成員關係測試

item in X(X為任何可迭代對象)

index

整數值

hex(X), bin(X), oct(X)

enter, exit

環境管理器

with obj as var:

get, set,

delete

描述符屬性

X.attr, X.attr=value, del X.attr

new

建立

在init之前建立對象

下面對常用的運算子方法的使用進行一下介紹。

建構函式和解構函式:init和del

它們的主要作用是進行對象的建立和回收,當執行個體建立時,就會調用init構造方法。當執行個體對象被收回時,解構函式del會自動執行。

>>> class Human(): ...   def init(self, n): ...     self.name = n ...       print("init ",self.name) ...   def del(self): ...     print("del") ...  >>> h = Human('Tim') init Tim >>> h = 'a' del

加減運算:add和sub

重載這兩個方法就可以在普通的對象上添加+-運算子操作。下面的代碼示範了如何使用+-運算子,如果將代碼中的sub方法去掉,再調用減號運算子就會出錯。

>>> class Computation(): ...   def init(self,value): ...     self.value = value ...   def add(self,other): ...     return self.value + other ...   def sub(self,other): ...     return self.value - other ...  >>> c = Computation(5) >>> c + 5 10 >>> c - 3 2

對象的字串表達形式:repr和str

這兩個方法都是用來表示對象的字串表達形式:print()、str()方法會調用到str方法,print()、str()和repr()方法會調用repr方法。從下面的例子可以看出,當兩個方法同時定義時,Python會優先搜尋並調用str方法。

>>> class Str(object): ...   def str(self): ...     return "str called"   ...   def repr(self): ...     return "repr called" ...  >>> s = Str() >>> print(s) str called >>> repr(s) 'repr called' >>> str(s) 'str called'

索引取值和賦值:getitem, setitem

通過實現這兩個方法,可以通過諸如 X[i] 的形式對對象進行取值和賦值,還可以對對象使用切片操作。

>>> class Indexer:   data = [1,2,3,4,5,6]   def getitem(self,index):     return self.data[index]   def setitem(self,k,v):     self.data[k] = v     print(self.data) >>> i = Indexer() >>> i[0] 1 >>> i[1:4] [2, 3, 4] >>> i[0]=10 [10, 2, 3, 4, 5, 6]

設定和訪問屬性:getattr、setattr

我們可以通過重載getattr和setattr來攔截對對象成員的訪問。getattr在訪問對象中不存在的成員時會自動調用。setattr方法用於在初始化對象成員的時候調用,即在設定dict的item時就會調用setattr方法。具體例子如下:

class A():   def init(self,ax,bx):     self.a = ax     self.b = bx   def f(self):     print (self.dict)   def getattr(self,name):     print ("getattr")   def setattr(self,name,value):     print ("setattr")     self.dict[name] = value  a = A(1,2) a.f() a.x a.x = 3 a.f()

上面代碼的運行結果如下,從結果可以看出,訪問不存在的變數x時會調用getattr方法;當init被調用的時候,賦值運算也會調用setattr方法。

setattr setattr {'a': 1, 'b': 2} getattr setattr {'a': 1, 'x': 3, 'b': 2}

迭代器對象: iter, next

Python中的迭代,可以直接通過重載getitem方法來實現,看下面的例子。


>>> class Indexer: ...   data = [1,2,3,4,5,6] ...   def getitem(self,index): ...       return self.data[index] ...  >>> x = Indexer() >>> for item in x: ...   print(item) ...  1 2 3 4 5 6

通過上面的方法是可以實現迭代,但並不是最好的方式。Python的迭代操作會優先嘗試調用iter方法,再嘗試getitem。迭代環境是通過iter去嘗試尋找iter方法來實現,而這種方法返回一個迭代器對象。如果這個方法已經提供,Python會重複調用迭代器對象的next()方法,直到發生StopIteration異常。如果沒有找到iter,Python才會嘗試使用getitem機制。下面看一下迭代器的例子。


class Next(object):   def init(self, data=1):     self.data = data   def iter(self):     return self   def next(self):     print("next called")     if self.data > 5:       raise StopIteration     else:       self.data += 1       return self.data for i in Next(3):   print(i) print("-----------") n = Next(3) i = iter(n) while True:   try:     print(next(i))   except Exception as e:     break

程式的運行結果如下:

next called 4 next called 5 next called 6 next called ----------- next called 4 next called 5 next called 6 next called

可見實現了iter和next方法後,可以通過for in的方式迭代遍曆對象,也可以通過iter()和next()方法迭代遍曆對象。

【相關推薦】

1. 精選:“php程式員工具箱”V0.1版本下載

2. Python免費視頻教程

3. Python基礎入門教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.