【Python基礎(chǔ)】Python中必須知道的5對(duì)魔術(shù)方法
原文作者:Yong Cui
翻譯:Lemon
譯文出品:Python數(shù)據(jù)之道

簡(jiǎn)介
calculate_mean_score?比?calculatemeanscore?更易于閱讀。您可能已經(jīng)知道,除了這種使用下劃線的常用方式之外,我們還為函數(shù)名稱(chēng)加上一個(gè)或兩個(gè)下劃線(例如,?_func,?__func),以表示這些函數(shù)供類(lèi)或模塊內(nèi)的私有使用。沒(méi)有下劃線前綴的名稱(chēng)被認(rèn)為是公共API。__func__。由于使用了雙下劃線,因此某些人將特殊方法稱(chēng)為 “dunder方法” 或簡(jiǎn)稱(chēng)為 “dunders” 。在本文中,我想回顧五對(duì)緊密相關(guān)的常用魔術(shù)方法,每對(duì)方法代表一個(gè) Python 概念。「Python數(shù)據(jù)之道」注:dunder 是 double underscore 的縮寫(xiě),即雙下劃線。
1. 實(shí)例化:?__new__?和?__init__
__init__。此方法用于定義實(shí)例對(duì)象的初始化行為。具體來(lái)說(shuō),在?__init__?方法中,您想要為創(chuàng)建的實(shí)例對(duì)象設(shè)置初始屬性。這是一個(gè)簡(jiǎn)單的示例:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
__init__方法時(shí),我們不會(huì)直接調(diào)用它。取而代之的是,?__init__方法成為該類(lèi)的構(gòu)造函數(shù)方法的構(gòu)建基礎(chǔ),該類(lèi)的構(gòu)造函數(shù)與?__init__方法具有相同的功能簽名。例如,要?jiǎng)?chuàng)建一個(gè)新的?Product?實(shí)例,請(qǐng)使用以下代碼:
product = Product("Vacuum", 150.0)
__init__方法最接近的是?__new__?方法,我們通常不會(huì)在自定義類(lèi)中實(shí)現(xiàn)該方法。本質(zhì)上,?__new__?方法實(shí)際上創(chuàng)建了實(shí)例對(duì)象,該實(shí)例對(duì)象被傳遞給?__init__?方法以完成初始化過(guò)程。__new__?和?__init__方法。
>>> class Product:
... def __new__(cls, *args):
... new_product = object.__new__(cls)
... print("Product __new__ gets called")
... return new_product
...
... def __init__(self, name, price):
... self.name = name
... self.price = price
... print("Product __init__ gets called")
...
>>> product = Product("Vacuum", 150.0)
Product __new__ gets called
Product __init__ gets called
2. 字符串(String)的表現(xiàn)形式:?__repr__?和?__str__
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f"Product({self.name!r}, {self.price!r})"
def __str__(self):
return f"Product: {self.name}, ${self.price:.2f}"
__repr__?方法應(yīng)該返回一個(gè)字符串,該字符串顯示如何創(chuàng)建實(shí)例對(duì)象。具體來(lái)說(shuō),可以將該字符串傳遞給?eval()來(lái)重新構(gòu)造實(shí)例對(duì)象。以下代碼段向您展示了這樣的操作:
>>> product = Product("Vacuum", 150.0)
>>> repr(product)
"Product('Vacuum', 150.0)"
>>> evaluated = eval(repr(product))
>>> type(evaluated)
<class '__main__.Product'>
__str__?方法可以返回有關(guān)實(shí)例對(duì)象的更多描述。應(yīng)該注意的是,?print()?函數(shù)使用?__str__方法來(lái)顯示與實(shí)例相關(guān)的信息,如下所示:
>>> print(product)
Product: Vacuum, $150.00
__repr__?方法通常是供開(kāi)發(fā)人員使用的,因此我們希望顯示實(shí)例化信息,而?__str__?方法是針對(duì)常規(guī)用戶(hù)的,因此我們希望顯示更多的信息。3. 迭代:?__iter__?和?__next__
for item in iterable:
# Operations go here
__iter__?特殊方法來(lái)完成的。另外,檢索迭代器的下一項(xiàng)涉及?__next__?特殊方法的實(shí)現(xiàn)。讓我們繼續(xù)前面的示例,并使我們的 Product 類(lèi)作為 for 循環(huán)中的迭代器工作:
>>> class Product:
... def __init__(self, name, price):
... self.name = name
... self.price = price
...
... def __str__(self):
... return f"Product: {self.name}, ${self.price:.2f}"
...
... def __iter__(self):
... self._free_samples = [Product(self.name, 0) for _ in range(3)]
... print("Iterator of the product is created.")
... return self
...
... def __next__(self):
... if self._free_samples:
... return self._free_samples.pop()
... else:
... raise StopIteration("All free samples have been dispensed.")
...
>>> product = Product("Perfume", 5.0)
>>> for i, sample in enumerate(product, 1):
... print(f"Dispense the next sample #{i}: {sample}")
...
Iterator of the product is created.
Dispense the next sample #1: Product: Perfume, $0.00
Dispense the next sample #2: Product: Perfume, $0.00
Dispense the next sample #3: Product: Perfume, $0.00
__iter__?方法中保存了免費(fèi)樣本 (free samples),這些樣本為自定義類(lèi)實(shí)例提供了迭代器。為了實(shí)現(xiàn)迭代行為,我們通過(guò)提供免費(fèi)樣本列表中的對(duì)象來(lái)實(shí)現(xiàn)?__next__?方法。當(dāng)我們用完免費(fèi)樣本時(shí),迭代結(jié)束。4. 上下文管理器:?__enter__?和?__exit__
with open('filename.txt') as file:
# Your file operations go here
with?語(yǔ)句的使用被稱(chēng)為上下文管理器技術(shù)。具體來(lái)說(shuō),在上面的文件操作示例中,?with?語(yǔ)句將為文件對(duì)象創(chuàng)建一個(gè)上下文管理器,并且在文件操作之后,上下文管理器將幫助我們關(guān)閉文件對(duì)象,以便共享資源(即文件) 可以用于其他進(jìn)程。__enter__?和?__exit__?方法。?__enter__?方法設(shè)置了上下文管理器,該上下文管理器為我們進(jìn)行操作準(zhǔn)備了所需的資源,而?__exit__?方法則是清理應(yīng)釋放的所有已使用資源,以使其可用。讓我們考慮下面的簡(jiǎn)單示例,其中包含先前的 “ Product” 類(lèi):
>>> class Product:
... def __init__(self, name, price):
... self.name = name
... self.price = price
...
... def __str__(self):
... return f"Product: {self.name}, ${self.price:.2f}"
...
... def _move_to_center(self):
... print(f"The product ({self}) occupies the center exhibit spot.")
...
... def _move_to_side(self):
... print(f"Move {self} back.")
...
... def __enter__(self):
... print("__enter__ is called")
... self._move_to_center()
...
... def __exit__(self, exc_type, exc_val, exc_tb):
... print("__exit__ is called")
... self._move_to_side()
...
>>> product = Product("BMW Car", 50000)
>>> with product:
... print("It's a very good car.")
...
__enter__ is called
The product (Product: BMW Car, $50000.00) occupies the center exhibit spot.
It's a very good car.
__exit__ is called
Move Product: BMW Car, $50000.00 back.
__enter__?方法。當(dāng)在 with 語(yǔ)句中完成該操作時(shí),將調(diào)用?__exit__?方法。__enter__和?__exit__方法來(lái)創(chuàng)建上下文管理器。使用上下文管理器“裝飾器”函數(shù),可以更輕松地完成此操作。5. 更精細(xì)的屬性訪問(wèn)控制:?__getattr__?和?__setattr__
__getattr__和?__setattr__方法來(lái)進(jìn)行控制。具體來(lái)說(shuō),訪問(wèn)實(shí)例對(duì)象的屬性時(shí)將調(diào)用?__getattr__?方法,而當(dāng)我們?cè)O(shè)置實(shí)例對(duì)象的屬性時(shí)將調(diào)用?__setattr__?方法。
>>> class Product:
... def __init__(self, name):
... self.name = name
...
... def __getattr__(self, item):
... if item == "formatted_name":
... print(f"__getattr__ is called for {item}")
... formatted = self.name.capitalize()
... setattr(self, "formatted_name", formatted)
... return formatted
... else:
... raise AttributeError(f"no attribute of {item}")
...
... def __setattr__(self, key, value):
... print(f"__setattr__ is called for {key!r}: {value!r}")
... super().__setattr__(key, value)
...
>>> product = Product("taBLe")
__setattr__ is called for 'name': 'taBLe'
>>> product.name
'taBLe'
>>> product.formatted_name
__getattr__ is called for formatted_name
__setattr__ is called for 'formatted_name': 'Table'
'Table'
>>> product.formatted_name
'Table'
__setattr__?方法。若要正確使用它,必須通過(guò)使用?super()?使用超類(lèi)方法。否則,它將陷入無(wú)限遞歸。__dict__?對(duì)象的一部分,因此不會(huì)調(diào)用?__getattr__。__getattribute__,它類(lèi)似于?__getattr__,但是每次訪問(wèn)屬性時(shí)都會(huì)被調(diào)用。在這方面,它類(lèi)似于?__setattr__,同樣,你應(yīng)使用super()實(shí)現(xiàn)?__getattribute__?方法,以避免無(wú)限遞歸錯(cuò)誤。小結(jié)
原文作者:Yong Cui 來(lái)源: https://medium.com/better-programming/5-pairs-of-magic-methods-in-python-you-should-know-f98f0e5356d6
往期精彩回顧
獲取一折本站知識(shí)星球優(yōu)惠券,復(fù)制鏈接直接打開(kāi):
https://t.zsxq.com/662nyZF
本站qq群704220115。
加入微信群請(qǐng)掃碼進(jìn)群(如果是博士或者準(zhǔn)備讀博士請(qǐng)說(shuō)明):
