面向物件快捷鍵
本章詳細介紹了Python中的各種內建函式、檔案I/O操作和過載概念。
Python內建函式
Python直譯器有很多稱為內建函式的函式,可以直接使用。在最新版本中,Python包含68個內建函式,如下表所示:
| 內建函式 | ||||
|---|---|---|---|---|
| abs() | dict() | help() | min() | setattr() |
| all() | dir() | hex() | next() | slice() |
| any() | divmod() | id() | object() | sorted() |
| ascii() | enumerate() | input() | oct() | staticmethod() |
| bin() | eval() | int() | open() | str() |
| bool() | exec() | isinstance() | ord() | sum() |
| bytearray() | filter() | issubclass() | pow() | super() |
| bytes() | float() | iter() | print() | tuple() |
| callable() | format() | len() | property() | type() |
| chr() | frozenset() | list() | range() | vars() |
| classmethod() | getattr() | locals() | repr() | zip() |
| compile() | globals() | map() | reversed() | __import__() |
| complex() | hasattr() | max() | round() | |
| delattr() | hash() | memoryview() | set() | |
本節簡要討論一些重要的函式:
len() 函式
len() 函式獲取字串、列表或集合的長度。它返回物件的長度或專案數量,其中物件可以是字串、列表或集合。
>>> len(['hello', 9 , 45.0, 24]) 4
len() 函式內部的工作方式類似於 list.__len__() 或 tuple.__len__()。因此,請注意,len() 僅適用於具有 __len__() 方法的物件。
>>> set1
{1, 2, 3, 4}
>>> set1.__len__()
4
然而,在實踐中,我們更傾向於使用 len() 而不是 __len__() 函式,原因如下:
它更高效。並且不需要編寫特定方法來拒絕訪問特殊方法,例如 __len__。
易於維護。
它支援向後相容性。
reversed(seq)
它返回反向迭代器。seq 必須是一個具有 __reversed__() 方法或支援序列協議(__len__() 方法和 __getitem__() 方法)的物件。當我們想要從後向前迴圈遍歷專案時,它通常用於 for 迴圈中。
>>> normal_list = [2, 4, 5, 7, 9]
>>>
>>> class CustomSequence():
def __len__(self):
return 5
def __getitem__(self,index):
return "x{0}".format(index)
>>> class funkyback():
def __reversed__(self):
return 'backwards!'
>>> for seq in normal_list, CustomSequence(), funkyback():
print('\n{}: '.format(seq.__class__.__name__), end="")
for item in reversed(seq):
print(item, end=", ")
最後的 for 迴圈列印普通列表的反向列表以及兩個自定義序列的例項。輸出顯示 reversed() 對所有三個序列都有效,但是當我們定義 __reversed__ 時,結果會有很大不同。
輸出
執行上面給出的程式碼時,您可以觀察到以下輸出:
list: 9, 7, 5, 4, 2, CustomSequence: x4, x3, x2, x1, x0, funkyback: b, a, c, k, w, a, r, d, s, !,
Enumerate
enumerate() 方法向可迭代物件新增計數器並返回列舉物件。
enumerate() 的語法如下:
enumerate(iterable, start = 0)
這裡的第二個引數 start 是可選的,預設情況下索引從零 (0) 開始。
>>> # Enumerate >>> names = ['Rajesh', 'Rahul', 'Aarav', 'Sahil', 'Trevor'] >>> enumerate(names) <enumerate object at 0x031D9F80> >>> list(enumerate(names)) [(0, 'Rajesh'), (1, 'Rahul'), (2, 'Aarav'), (3, 'Sahil'), (4, 'Trevor')] >>>
因此,enumerate() 返回一個迭代器,該迭代器產生一個元組,該元組對傳遞的序列中的元素進行計數。由於返回值是迭代器,因此直接訪問它並沒有多大用處。enumerate() 的更好方法是在 for 迴圈中進行計數。
>>> for i, n in enumerate(names):
print('Names number: ' + str(i))
print(n)
Names number: 0
Rajesh
Names number: 1
Rahul
Names number: 2
Aarav
Names number: 3
Sahil
Names number: 4
Trevor
標準庫中還有許多其他函式,這裡列出了其他一些更常用的函式:
hasattr、getattr、setattr 和 delattr,允許透過其字串名稱操作物件的屬性。
all 和 any,它們接受一個可迭代物件,如果所有專案或任何專案評估結果為真,則返回 True。
zip,它接受兩個或多個序列並返回一個新的元組序列,其中每個元組包含每個序列中的單個值。
檔案 I/O
檔案的概念與面向物件程式設計術語相關。Python 將作業系統提供的介面封裝在允許我們使用檔案物件的抽象中。
open() 內建函式用於開啟檔案並返回檔案物件。它是兩個引數最常用的函式:
open(filename, mode)
open() 函式呼叫兩個引數,第一個是檔名,第二個是模式。這裡的模式可以是 'r'(只讀模式)、'w'(只寫,具有相同名稱的現有檔案將被擦除)和 'a'(開啟檔案以進行追加,寫入檔案的所有資料都將自動新增到末尾)。'r+' 開啟檔案進行讀寫。預設模式是隻讀。
在 Windows 上,附加到模式的 'b' 以二進位制模式開啟檔案,因此還有 'rb'、'wb' 和 'r+b' 等模式。
>>> text = 'This is the first line'
>>> file = open('datawork','w')
>>> file.write(text)
22
>>> file.close()
在某些情況下,我們只想追加到現有檔案而不是覆蓋它,為此我們可以提供 'a' 值作為模式引數,以追加到檔案的末尾,而不是完全覆蓋現有檔案內容。
>>> f = open('datawork','a')
>>> text1 = ' This is second line'
>>> f.write(text1)
20
>>> f.close()
開啟檔案進行讀取後,我們可以呼叫 read、readline 或 readlines 方法來獲取檔案的內容。read 方法將檔案的全部內容作為 str 或 bytes 物件返回,具體取決於第二個引數是否為 'b'。
為了可讀性,並避免一次性讀取大型檔案,直接在檔案物件上使用 for 迴圈通常更好。對於文字檔案,它將一次讀取一行,我們可以在迴圈體中對其進行處理。但是,對於二進位制檔案,最好使用 read() 方法讀取固定大小的資料塊,並傳遞一個引數來指定要讀取的最大位元組數。
>>> f = open('fileone','r+')
>>> f.readline()
'This is the first line. \n'
>>> f.readline()
'This is the second line. \n'
寫入檔案,透過檔案物件的 write 方法將字串(對於二進位制資料為位元組)物件寫入檔案。writelines 方法接受一系列字串並將每個迭代值寫入檔案。writelines 方法不會在序列中的每個專案之後附加換行符。
最後,當我們完成檔案讀取或寫入時,應呼叫 close() 方法,以確保所有緩衝寫入都寫入磁碟,檔案已正確清理,並且與檔案繫結的所有資源都已釋放回作業系統。呼叫 close() 方法是一種更好的方法,但在技術上,當指令碼退出時,這將自動發生。
方法過載的替代方法
方法過載是指擁有多個具有相同名稱但接受不同引數集的方法。
對於單個方法或函式,我們可以自己指定引數的數量。根據函式定義,它可以呼叫零個、一個、兩個或多個引數。
class Human:
def sayHello(self, name = None):
if name is not None:
print('Hello ' + name)
else:
print('Hello ')
#Create Instance
obj = Human()
#Call the method, else part will be executed
obj.sayHello()
#Call the method with a parameter, if part will be executed
obj.sayHello('Rahul')
輸出
Hello Hello Rahul
預設引數
函式也是物件
可呼叫物件是可以接受某些引數並可能返回物件的任何物件。函式是 Python 中最簡單的可呼叫物件,但還有其他物件,例如類或某些類例項。
Python 中的每個函式都是一個物件。物件可以包含方法或函式,但物件不一定是函式。
def my_func():
print('My function was called')
my_func.description = 'A silly function'
def second_func():
print('Second function was called')
second_func.description = 'One more sillier function'
def another_func(func):
print("The description:", end=" ")
print(func.description)
print('The name: ', end=' ')
print(func.__name__)
print('The class:', end=' ')
print(func.__class__)
print("Now I'll call the function passed in")
func()
another_func(my_func)
another_func(second_func)
在上面的程式碼中,我們可以將兩個不同的函式作為引數傳遞到我們的第三個函式中,併為每個函式獲得不同的輸出:
The description: A silly function The name: my_func The class:Now I'll call the function passed in My function was called The description: One more sillier function The name: second_func The class: Now I'll call the function passed in Second function was called
可呼叫物件
正如函式是可以設定屬性的物件一樣,也可以建立一個可以像函式一樣呼叫的物件。
在 Python 中,任何具有 __call__() 方法的物件都可以使用函式呼叫語法進行呼叫。