溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python面向?qū)ο蟮氖褂冒咐?/h1>
發(fā)布時間:2022-03-16 13:51:24 來源:億速云 閱讀:145 作者:小新 欄目:開發(fā)技術

這篇文章給大家分享的是有關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ū)ο蟮氖褂冒咐?></p><p ># 14/9/2019</p><p >可以不使用構(gòu)造函數(shù)將所有邏輯都放入__init__并使用*args,**kwargs和一堆if語句來解決,但是比較丑陋,沒有可讀性和可維護性。</p><p ><strong>4. 獲取對象信息</strong></p><p >Python提供了幾個函數(shù)以便我們更好的獲取對象的信息,這些函數(shù)包括:type、isinstance和dir。</p><p >其中type():用于判斷對象類型:</p><pre>>>> type(None) <class 'NoneType'> >>> type(abs) <class 'builtin_function_or_method'></pre><p >對類對象type()返回的是對應class類型。下面是判斷兩個變量的type類型是否相同:</p><pre>>>> type(11) == type(22) True >>> type('abc') == str True >>> type('abc') == type(33) False</pre><p >isinstance():可以顯示對象是否是某種類型</p><pre>>>> class Husty(Dog): ... pass ... >>> a = Animal() >>> b = Dog() >>> c = Husty() >>> isinstance(c,Husty) True >>> isinstance(c,Dog) True >>> isinstance(c,Animal) True >>> isinstance(b,Husty) False</pre><p >Husty是Husty、Dog、Animal類型的對象,卻不能說Dog是Husty的對象。</p><p >dir():用于獲取一個對象的所有方法和屬性。返回值是一個包含字符串的list:</p><pre>>>> dir('abc') ['__add__', '__class__',&hellip;&hellip; '__hash__', '__init__', '__i &hellip;&hellip;'isalnum 'isidentifier', 'islower', &hellip;&hellip; 'translate', 'upper', 'zfill']</pre><p >其中,類似__xx__的屬性和方法都是有特殊用途的。如果調(diào)用len()函數(shù)視圖獲取一個對象的長度,其實在len()函數(shù)內(nèi)部會自動去調(diào)用該對象的__len__()方法。</p><p ><strong>5. Iterator和切片</strong></p><p >如果直接對Iterator切片,則會得到TypeError,指出生成器對象不可下標反問,但是有一個技巧:</p><pre>import itertools s = itertools.islice(range(50), 10, 20) for val in s: ...</pre><p >使用itertools.islice,可以創(chuàng)建一個islice對象,該對象是生成所需項目的迭代器。但是,這會消耗所有生成器項,直到分片開始為止,而且還會消耗islice對象中的所有項。</p><p ><strong>6. 跳過一些行</strong></p><p >有時,必須使用已知以可變數(shù)量的不需要的行(例如注釋)。也可以使用itertools:</p><pre>string_from_file = """ // Author: ... // License: ... // // Date: ... Actual content... """  import itertools for line in itertools.dropwhile(lambda line: line.startswith("//"), string_from_file.split("\n")): print(line)</pre><p >該代碼段僅在初始注釋部分之后產(chǎn)生行。如果只想在迭代器的開頭丟棄并且不知道其中有多少個項目,則此方法很有用。</p><p ><strong>7. 命名切片</strong></p><p >使用大量硬編碼的索引值會很容易引起代碼繁瑣和破壞代碼可讀性。常用的技巧是對索引值使用常量,除此之外我們可以使用命名切片:</p><p ><img src=感謝各位的閱讀!關于“python面向?qū)ο蟮氖褂冒咐边@篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI