python特殊函式 cmp

2022-02-27 17:02:14 字數 1735 閱讀 4048

__cmp__

對 int、str 等內建資料型別排序時,python的 sorted() 按照預設的比較函式 cmp 排序,但是,如果對一組 student 類的例項排序時,就必須提供我們自己的特殊方法

__cmp__

():class

student(object):

def__init__

(self, name, score):

self.name =name

self.score =score

def__str__

(self):

return

'(%s: %s)

' %(self.name, self.score)

__repr__ = __str__

def__cmp__

(self, s):

if self.name return -1

elif self.name >s.name:

return 1

else

:

return

0上述 student 類實現了__cmp__()方法,

__cmp__用例項自身self和傳入的例項 s 進行比較,如果 self 應該排在前面,就返回 -1,如果 s 應該排在前面,就返回1,如果兩者相當,返回 0。

student類實現了按name進行排序:

>>> l = [student('

tim', 99), student('

bob', 88), student('

alice

', 77)]

>>> print

sorted(l)

[(alice: 77), (bob: 88), (tim: 99)]

注意: 如果list不僅僅包含 student 類,則

__cmp__

可能會報錯:

l = [student('

tim', 99), student('

bob', 88), 100, '

hello']

print

sorted(l)

請思考如何解決。

class

student(object):

def__init__

(self, name, score):

self.name =name

self.score =score

def__str__

(self):

return

'(%s: %s)

' %(self.name, self.score)

__repr__ = __str__

def__cmp__

(self, s):

if(self.scorereturn 1

if(self.score>s.score):

return -1

if(self.score==s.score):

if(self.name>s.name):

return 1;

if(self.namereturn -1

return

0l = [student('

tim', 99), student('

bob', 88), student('

alice

', 99)]

print sorted(l)

Python特殊函式

object中因為有 repr 方法,所以直接列印例項化物件會有下面這句列印出來 main clanguage object at 0x000001a7275221d0 在類中重寫 repr 函式,class clanguage def init self self.name c語言中文網 self...

關於sort 函式編寫cmp函式

sort 函式中,一般是用於陣列中整形資料的排序,但是 遇見結構體中有多個整形資料,sort的功能就開始迷糊了,所以我們需要在結構體中定下需要比較哪組,第一 sort begin,begin n 第二 利用cmp進行倒序,公升序 bool compare int a,int b sort a,a 2...

python 內建函式和特殊函式

2 特殊函式 輸入輸出 記憶體相關 檔案操作相關 模組相關 幫助 呼叫相關 檢視內建屬性 字串型別 的執行 exec 動態執行 沒有返回值 complie 將乙個字串編譯成位元組 例子 in 8 eval 3 5 2 8 10 21 out 8 35.0 in 9 exec print 這是exec...