摘要:第二章與的無縫集成基本特殊方法筆記中有有一些特殊的方法它們?cè)试S我們的類和更好的集成和方法通常方法表示的對(duì)象對(duì)用戶更加友好這個(gè)方法是有對(duì)象的方法實(shí)現(xiàn)的什么時(shí)候重寫跟非集合對(duì)象一個(gè)不包括其他集合對(duì)象的簡單對(duì)象這類對(duì)象格式通常不會(huì)特別復(fù)
第二章 與Python的無縫集成----基本特殊方法.(Mastering Objecting-oriented Python 筆記)
python中有有一些特殊的方法,它們?cè)试S我們的類和python更好的集成
__repr__():
__str__()
__format__()
__hash__()
__bool__()
__bytes__()
__lt__()
__le__()
__eq__()
__ne__()
__gt__()
__ge__()
__new__()
__del__()
2.1 __repr__()和__str__()方法
通常str()方法表示的對(duì)象對(duì)用戶更加友好.這個(gè)方法是有對(duì)象的__str__()方法實(shí)現(xiàn)的.
什么時(shí)候重寫 __str__()跟__repr__()
非集合對(duì)象: 一個(gè)不包括其他集合對(duì)象的"簡單"對(duì)象,這類對(duì)象格式通常不會(huì)特別復(fù)雜
集合對(duì)象:一個(gè)包括集合的對(duì)象,這類對(duì)象的格式化會(huì)非常復(fù)雜.
問題1: 什么是集合?
class Card(object): def __init__(self, rank, suit): self.suit = suit self.rank = rank self.hard, self.soft = self._points() def __repr__(self): return "{__class__.__name__}(suit = {suit!r} , rank = {rank!r})".format( __class__=self.__class__, **self.__dict__ ) def __str__(self): return "{rank}{suit}".format(**self.__dict__) class NumberCard(Card): def _points(self): return int(self.rank), int(self.rank) x = NumberCard("2", "?") # 注意下面是重寫后的 print(str(x)) # 2? print(x) # 2? print(repr(x)) # NumberCard(suit = "?" , rank = "2")
注意:‘{0!r}".format()和"{0!s}".format()并不會(huì)調(diào)用__format__()方法,它們會(huì)調(diào)用__repr__()或者__str__().
內(nèi)置hash()函數(shù)調(diào)用了__hash__()方法.哈希是一種將復(fù)雜的值簡化為小整數(shù)的計(jì)算方式.
python有兩個(gè)哈希庫:
hashlib
zip 有兩個(gè)搞笑的哈希函數(shù)adler32()和crc32()
hash()函數(shù)主要被用來創(chuàng)建set,forzenset,dict這些集合類的鍵.這些集合利用了不可變對(duì)象的哈希值來高效的查找集合中的對(duì)象
并非每個(gè)對(duì)象都需要提供一個(gè)哈希值,尤其是,當(dāng)我們創(chuàng)建一個(gè)包含有狀態(tài),可改變對(duì)象的類時(shí).這類不應(yīng)該返回哈希值,__hash__的定義 應(yīng)該是None
等價(jià)比較有三個(gè)層次:
哈希值相等:意味著兩個(gè)結(jié)果可能相等.哈希值是判斷兩個(gè)對(duì)象有可能相等的快捷方式,如果哈希值不同,兩個(gè)對(duì)象不可能相等,也不可能是同一個(gè)對(duì)象.
比較結(jié)果相等:意味著兩個(gè)對(duì)象的哈希值已經(jīng)是相等的,這個(gè)比較用的是==運(yùn)算符.如果結(jié)果相等,那么兩個(gè)對(duì)象的有可能是同一個(gè).
IDD 相等:這意味著兩個(gè)對(duì)象是同一個(gè)對(duì)象,它們的哈希值仙童,并且使用==的比較結(jié)果相等,這個(gè)比較是用的是is運(yùn)算符.
**基本哈希法(Fundametal Law of Hash):比較相等的對(duì)象的哈希值一定相等.
class Card(object): def __init__(self, rank, suit, hard, soft): self.suit = suit self.rank = rank self.hard = hard self.soft = soft def __repr__(self): return "{__class__.__name__}(suit = {suit!r} , rank = {rank!r})".format( __class__=self.__class__, **self.__dict__ ) def __str__(self): return "{rank}{suit}".format(**self.__dict__) class NumberCard(Card): def __init__(self, rank, suit): super().__init__(str(rank), suit, rank, rank) class AceCard(Card): def __init__(self, rank, suit): super(AceCard, self).__init__("A", suit, 1, 11) class FaceCard(Card): def __init__(self, rank, suit): super(FaceCard, self).__init__({11: "J", 12: "Q", 13: "K"}[rank], suit, 10, 10) c1 = AceCard(1,"?") c2 = AceCard(1,"?") print(id(c1),id(c2)) # 52067024 52067120
id()值不同意味著是不同的對(duì)象.
**is測(cè)試基于id()的值,哈希值根據(jù)id()值來計(jì)算的`
下面是一個(gè)重載了__hash__()和__eq__()定義的簡單類.
class Card2(object): def __init__(self, rank, suit, hard, soft): self.suit = suit self.rank = rank self.hard = hard self.soft = soft def __repr__(self): return "{__class__.__name__}(suit = {suit!r} , rank = {rank!r})".format( __class__=self.__class__, **self.__dict__ ) def __str__(self): return "{rank}{suit}".format(**self.__dict__) def __eq__(self, other): return self.suit == other.suit and self.rank == other.rank def __hash__(self): return hash(self.suit) ^ hash(self.rank) class AceCard2(Card2): insure = True def __init__(self, rank, suit): super().__init__("A", suit, 1, 11) c1 = AceCard2(1, "?") c2 = AceCard2(1, "?") print(id(c1), id(c2)) # id 是不相同的 print(c1 is c2) # False print(hash(c1), hash(c2)) # hash是相同的 print(c1 == c2) # True print(set([c1,c2])) # {AceCard2(suit = "?" , rank = "A")}
下面的類層級(jí)結(jié)構(gòu)中,我們重載了可變對(duì)象的 __hash__()和__eq__()
class Card3(object): def __init__(self, rank, suit, hard, soft): self.suit = suit self.rank = rank self.hard = hard self.soft = soft def __repr__(self): return "{__class__.__name__}(suit = {suit!r} , rank = {rank!r})".format( __class__=self.__class__, **self.__dict__ ) def __str__(self): return "{rank}{suit}".format(**self.__dict__) def __eq__(self, other): return self.suit == other.suit and self.rank == other.rank __hash__ = None class AceCard3(Card3): insure = True def __init__(self, rank, suit): super().__init__("A", suit, 1, 11) cc1 = AceCard3(1, "?") cc2 = AceCard3(1, "?") print(id(cc1), id(cc2)) # id 是不相同的 >>>8813424 8813616 print(cc1 is cc2) # False
>>>print(hash(cc1), hash(cc2)) # TypeError: unhashable type: "AceCard3" Traceback (most recent call last): File "E:/cnki/cloudrepository/DataCleansingSystem/src/test/test_excel.py", line 113, inprint(set([cc1,cc2])) # {AceCard2(suit = "?" , rank = "A")} TypeError: unhashable type: "AceCard3"
__hash__被設(shè)置為None,所以這些用Card3生成的對(duì)象不可以被哈希,也就無法通過hash()函數(shù)提供的哈希值了.
print(cc1 == cc2) # True print(set([cc1,cc2])) # TypeError: unhashable type: "AceCard3"
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/44498.html
摘要:這些基本的特殊方法在類中定義中幾乎總是需要的。和方法對(duì)于一個(gè)對(duì)象,有兩種字符串表示方法。這些都和內(nèi)置函數(shù)以及方法緊密結(jié)合。帶有說明符的合理響應(yīng)是返回。 注:原書作者 Steven F. Lott,原書名為 Mastering Object-oriented Python 有許多特殊方法允許類與Python緊密結(jié)合,標(biāo)準(zhǔn)庫參考將其稱之為基本,基礎(chǔ)或本質(zhì)可能是更好的術(shù)語。這些特殊...
摘要:比較運(yùn)算符方法有六個(gè)比較運(yùn)算符。根據(jù)文檔,其映射工作如下第七章創(chuàng)建數(shù)字我們會(huì)再次回到比較運(yùn)算符這塊。同一個(gè)類的對(duì)象的比較實(shí)現(xiàn)我們來看看一個(gè)簡單的同一類的比較通過觀察一個(gè)更完整的類現(xiàn)在我們已經(jīng)定義了所有六個(gè)比較運(yùn)算符。 注:原書作者 Steven F. Lott,原書名為 Mastering Object-oriented Python __bool__()方法 Python對(duì)假有個(gè)很...
摘要:有三個(gè)用例通過和方法定義相等性檢測(cè)和值不可變對(duì)象對(duì)于有些無狀態(tài)對(duì)象,例如這些不能被更新的類型。請(qǐng)注意,我們將為不可變對(duì)象定義以上兩個(gè)。 注:原書作者 Steven F. Lott,原書名為 Mastering Object-oriented Python __hash__() 方法 內(nèi)置hash()函數(shù)會(huì)調(diào)用給定對(duì)象的__hash__()方法。這里hash就是將(可能是復(fù)雜的)值縮減...
摘要:當(dāng)引用計(jì)數(shù)為零,則不再需要該對(duì)象且可以銷毀。這表明當(dāng)變量被刪除時(shí)引用計(jì)數(shù)正確的變?yōu)榱恪7椒ㄖ荒茉谘h(huán)被打破后且引用計(jì)數(shù)已經(jīng)為零時(shí)調(diào)用。這兩步的過程允許引用計(jì)數(shù)或垃圾收集刪除已引用的對(duì)象,讓弱引用懸空。這允許在方法設(shè)置對(duì)象屬性值之前進(jìn)行處理。 注:原書作者 Steven F. Lott,原書名為 Mastering Object-oriented Python __del__()方法 ...
摘要:這正是使用編輯器的基本形式。禁用啟動(dòng)消息即顯示所有教程信息的頁面。因此,只使用編輯器并且完美支持所有這些語言將會(huì)大大提高工作效率。結(jié)語正如你所見,明顯是最好的編輯器。 本文是realpython.com繼《將Sublime Text 3打造為Python全棧開發(fā)環(huán)境及》和《Vim與Python真乃天作之合》,又一篇關(guān)于如何配置Python IDE的文章。這一次,主角變成了與Vim同樣...
閱讀 3616·2023-04-26 01:43
閱讀 3005·2021-10-14 09:42
閱讀 5558·2021-09-30 09:59
閱讀 2201·2021-09-04 16:40
閱讀 1235·2019-08-30 15:52
閱讀 860·2019-08-29 17:09
閱讀 2030·2019-08-26 13:37
閱讀 3457·2019-08-26 10:20