本章詳細(xì)討論P(yáng)ython中的各種內(nèi)置函數(shù),文件I/O操作和重載概念。
Python解釋器有許多稱為內(nèi)置函數(shù)的函數(shù),可以隨時(shí)使用。 在其最新版本中,Python包含68個(gè)內(nèi)置函數(shù),如下表所列 -
| — | — | — | — | — |
|---|---|---|---|---|
| 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() | - |
本節(jié)簡(jiǎn)要介紹一些重要函數(shù)/功能 -
len()函數(shù)
len()函數(shù)獲取字符串,列表或集合的長(zhǎng)度。 它返回對(duì)象的項(xiàng)目的長(zhǎng)度或數(shù)量,其中對(duì)象可以是字符串,列表或集合。
>>> len(['hello', 9 , 45.0, 24])
4
len()函數(shù)內(nèi)部工作方式如list.__len__()或tuple.__ len __()。 因此,請(qǐng)注意,len()僅適用于具有__len __()方法的對(duì)象。
>>> set1
{1, 2, 3, 4}
>>> set1.__len__()
4
但是,在實(shí)踐中,我們更頃向于使用len()而不是__len __()函數(shù),原因如下 -
__len__這樣的特殊方法是沒(méi)有必要的。Reversed(seq)方法
它返回反向迭代器。 seq必須是具有__reversed __()方法或支持序列協(xié)議(__len __()方法和__getitem __()方法)的對(duì)象。 當(dāng)我們想從后到前循環(huán)項(xiàng)目時(shí),它通常用于循環(huán)。
>>> 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循環(huán)打印正常列表的反轉(zhuǎn)列表,以及兩個(gè)自定義序列的實(shí)例。 輸出顯示revers()適用于它們中的所有三個(gè),但是當(dāng)定義__reversed__時(shí),結(jié)果會(huì)有很大不同。
執(zhí)行上面給出的代碼時(shí),可以觀察到以下輸出 -
list: 9, 7, 5, 4, 2,
CustomSequence: x4, x3, x2, x1, x0,
funkyback: b, a, c, k, w, a, r, d, s, !,
枚舉enumerate()方法向iterable添加一個(gè)計(jì)數(shù)器并返回枚舉對(duì)象。enumerate()的語(yǔ)法是 -
enumerate(iterable, start = 0)
這里第二個(gè)參數(shù)起始是可選的,默認(rèn)情況下索引從零開(kāi)始(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()·返回一個(gè)迭代器,它產(chǎn)生一個(gè)元組,用于保持傳遞的序列中元素的計(jì)數(shù)。 由于返回值是一個(gè)迭代器,直接訪問(wèn)它并沒(méi)有多大用處。 enumerate()的更好方法是將計(jì)數(shù)保持在for循環(huán)中。
>>> 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
標(biāo)準(zhǔn)庫(kù)中還有許多其他功能,下面是另一些更廣泛使用的功能列表 -
hasattr,getattr,setattr和delattr,它允許對(duì)象的屬性由其字符串名稱操作。all和any,接受可迭代對(duì)象,如果所有或任何項(xiàng)目評(píng)估為真,則返回True。nzip,它采用兩個(gè)或多個(gè)序列并返回一個(gè)新的元組序列,其中每個(gè)元組包含每個(gè)序列的單個(gè)值。文件的概念與術(shù)語(yǔ)面向?qū)ο缶幊滔嚓P(guān)。 Python封裝了操作系統(tǒng)在抽象中提供的接口,使我們可以使用文件對(duì)象。
open()內(nèi)置函數(shù)用于打開(kāi)文件并返回文件對(duì)象。 它是兩個(gè)參數(shù)中最常用的函數(shù) -
open(filename, mode)
open()函數(shù)調(diào)用兩個(gè)參數(shù),第一個(gè)是文件名,第二個(gè)是模式。 這里的模式可以是只讀模式的'r',只有寫(xiě)入的模式'w'(同名的現(xiàn)有文件將被刪除),'a'打開(kāi)要附加的文件,任何寫(xiě)入文件的數(shù)據(jù)都會(huì)自動(dòng)添加 到最后。 'r +'打開(kāi)文件進(jìn)行讀寫(xiě)。 默認(rèn)模式是只讀的。
在窗口中,模式附加的'b'以二進(jìn)制模式打開(kāi)文件,所以也有'rb','wb'和'r + b'等模式。
>>> text = 'This is the first line'
>>> file = open('datawork','w')
>>> file.write(text)
22
>>> file.close()
在某些情況下,我們只想附加到現(xiàn)有文件而不是覆蓋它,因?yàn)榭梢蕴峁┲?code>'a'作為模式參數(shù),附加到文件的末尾,而不是完全覆蓋現(xiàn)有文件內(nèi)容。
>>> f = open('datawork','a')
>>> text1 = ' This is second line'
>>> f.write(text1)
20
>>> f.close()
當(dāng)打開(kāi)一個(gè)文件進(jìn)行讀取,可以調(diào)用read,readline或readlines方法來(lái)獲取文件的內(nèi)容。 read方法將文件的全部?jī)?nèi)容作為str或bytes對(duì)象返回,具體取決于第二個(gè)參數(shù)是否為'b'。
為了便于閱讀,并且為了避免一次性讀取大文件,通常最好直接在文件對(duì)象上使用for循環(huán)。 對(duì)于文本文件,它將逐行讀取每一行,并且可以在循環(huán)體內(nèi)處理它。 但對(duì)于二進(jìn)制文件,最好使用read()方法讀取固定大小的數(shù)據(jù)塊,并傳遞參數(shù)以獲取最大字節(jié)數(shù)。
>>> f = open('fileone','r+')
>>> f.readline()
'This is the first line. \n'
>>> f.readline()
'This is the second line. \n'
通過(guò)對(duì)文件對(duì)象的寫(xiě)入方法寫(xiě)入文件將向該文件寫(xiě)入一個(gè)字符串(二進(jìn)制數(shù)據(jù)的字節(jié))對(duì)象。 writelines方法接受一系列字符串并將每個(gè)迭代值寫(xiě)入文件。 writelines方法不在序列中的每個(gè)項(xiàng)目之后追加一個(gè)新行。
最后,在完成讀取或?qū)懭胛募r(shí),應(yīng)調(diào)用close()方法,以確保將任何緩沖寫(xiě)入寫(xiě)入磁盤(pán),文件已被正確清理,并將與該文件綁定的所有資源釋放回操作系統(tǒng)。 調(diào)用close()方法是一個(gè)更好的方法,但從技術(shù)上講,這將在腳本存在時(shí)自動(dòng)發(fā)生。
方法重載的替代方法
方法重載是指具有多個(gè)接受不同參數(shù)集的同名方法。
給定單個(gè)方法或函數(shù),可以指定自己的參數(shù)數(shù)量。 根據(jù)函數(shù)定義,可以使用零個(gè),一個(gè),兩個(gè)或多個(gè)參數(shù)來(lái)調(diào)用它。
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')
執(zhí)行上面示例代碼,得到以下結(jié)果 -
Hello
Hello Rahul
函數(shù)也是對(duì)象
可調(diào)用對(duì)象是一個(gè)對(duì)象可以接受一些參數(shù),并可能返回一個(gè)對(duì)象。 函數(shù)是Python中最簡(jiǎn)單的可調(diào)用對(duì)象,但也有其他類似于類或某些類實(shí)例。
Python中的每個(gè)函數(shù)都是一個(gè)對(duì)象。 對(duì)象可以包含方法或函數(shù),但對(duì)象不是必需的函數(shù)。
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)
在上面的代碼中,可以將兩個(gè)不同的函數(shù)作為參數(shù)傳遞給第三個(gè)函數(shù),并為每個(gè)函數(shù)獲取不同的輸出 -
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
可調(diào)用的對(duì)象
就像函數(shù)是可以在其上設(shè)置屬性的對(duì)象一樣,可以創(chuàng)建一個(gè)可以被調(diào)用的對(duì)象,就像它是一個(gè)函數(shù)一樣。
在Python中,可以使用函數(shù)調(diào)用語(yǔ)法來(lái)調(diào)用帶有__call __()方法的任何對(duì)象。