您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關python面向?qū)ο蟮氖褂冒咐膬?nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
面向?qū)ο?/strong>
1. 創(chuàng)建支持With語句的對象
我們都知道如何使用打開或關閉語句,例如打開文件或獲取鎖,但是如何實現(xiàn)自己的方法呢?
可以使用__enter__和__exit__方法實現(xiàn):
class Connection: def __init__(self): ... def __enter__(self): # Initialize connection... def __exit__(self, type, value, traceback): # Close connection... with Connection() as c: # __enter__() executes ... # conn.__exit__() executes
這是在Python中實現(xiàn)上下文管理的最常見方法,但是有一種更簡單的方法:
from contextlib import contextmanager @contextmanager def tag(name): print(f"<{name}>") yield print(f"</{name}>") with tag("h2"): print("This is Title.")
上面的代碼段使用contextmanager管理器裝飾器實現(xiàn)了內(nèi)容管理協(xié)議。進入with塊時,執(zhí)行標記函數(shù)的第一部分(在yield之前),然后執(zhí)行該塊,最后執(zhí)行其余的標記函數(shù)。
2. 重載運算符號的技巧
考慮到有很多比較運算符:__lt__ , __le__ , __gt__,對于一個類實現(xiàn)所有比較運算符可能會很煩人。這時候可以使用functools.total_ordering:
from functools import total_ordering @total_ordering class Number: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value def __eq__(self, other): return self.value == other.value print(Number(20) > Number(3)) print(Number(1) < Number(5)) print(Number(15) >= Number(15)) print(Number(10) <= Number(2))
該代碼使用total_ordering裝飾器用于簡化為類實現(xiàn)實例排序的過程。只需要定義__lt__和__eq__。
3. 在一個類中定義多個構(gòu)造函數(shù)
函數(shù)重載是編程語言中非常常見的功能。即使Python不能重載正常的函數(shù),我們也可以使用類方法重載構(gòu)造函數(shù):
import datetime class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day @classmethod def today(cls): t = datetime.datetime.now() return cls(t.year, t.month, t.day) d = Date.today() print(f"{d.day}/{d.month}/{d.year}")
感謝各位的閱讀!關于“python面向?qū)ο蟮氖褂冒咐边@篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。