1. 程式人生 > Python進階應用教學 >25 Python 內建函式

25 Python 內建函式

Python 直譯器內建了很多函式,不用 import 即可使用這些內建函式。本小節講解了 Python 中常見的內建函式,我們將這些函式分為 7 大類:

類別 功能
系統幫助 獲取函式的使用幫助
檔案 IO 讀取標準輸入、寫標準輸出、開啟檔案
型別轉換 將整數轉換為字串、將字串轉換為整數
數學運算 常見的數學運算函式,例如:max 和 min
複合資料型別 列表、元組、字典等資料型別的構造
對序列的操作 對序列進行排序、篩選、對映
面向物件相關 判斷型別之間的歸屬關係

1. 系統幫助

1.1 列出物件的屬性

>>> import sys
>>
> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loade r__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdou t__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegac ywindowsfsencoding', '_getframe', '_home', '
_mercurial', '_xoptions', 'api_versi on', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteord er', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont _write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', ... 省略 ... ] >>
>
  • 內建函式 dir(object) 用於列出物件 object 中的屬性
  • import sys 引入模組 sys
  • dir(sys) 列出模組 sys 定義的屬性名、函式名、類名

1.2 獲取物件的幫助文件

>>> help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its biggest item.    
  • help 命令用於獲取指定物件的幫助
  • help(max) 獲取內建函式 max 的幫助
>>> import sys
>>> help(sys.exit)
Help on built-in function exit in module sys:

exit(...)
    exit([status])

    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is an integer, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).
  • help(sys.exit) 獲取模組 sys 的函式 exit 的幫助

2. 檔案 IO

2.1 讀取使用者輸入

>>> line = input()
abc
>>> line
'abc'
  • 內建函式 input() 用於讀取使用者輸入的一行文字
  • input() 讀取使用者輸入的一行文字
>>> line = input('Input a number: ')
Input a number: 123
>>> line
'123'
  • input('Input a number: ') 首先列印提示符 'Input a number: ',然後再讀取使用者輸入

2.2 列印輸出

>>> print('hello')
hello
>>> print('hello', 'world')
hello world
  • 內建函式 print 列印文字到螢幕
  • 預設情況下,print() 輸出會加上換行

如果不需要換行,可以加上引數 end =’’,示例如下:

print('a', end = '')
print('b', end = '')
print('c', end = '')
print()

執行程式,輸出結果:

abc

2.3 開啟檔案

>>> file = open('test.txt')
>>> file.readline()
the first line
  • 函式 open(path) 開啟指定路徑 path 的檔案
  • 呼叫 file 物件的 readline() 方法返回一行

3. 型別轉換

3.1 將字串轉換為整數

>>> number = int('123')
>>> number
123
  • 函式 int(string) 將字串 string 轉換為整數

3.2 將字串轉換為浮點數

>>> number = float('123.456')
>>> number
123.456
  • 函式 float(string) 將字串 string 轉換為浮點數

3.2 將數值轉換為字串

>>> string = str(123)
>>> string
'123'
>>> string = str(123.456)
>>> string
'123.456'
  • 函式 str(number) 將數值轉換為字串
  • str(123) 將整數轉換為字串
  • str(123.456) 將浮點數轉換為字串

4. 數學運算

>>> abs(-1)
1
>>> round(1.4)
1
>>> round(1.5)
2
  • abs(number) 計算 number 的絕對值
  • round(number) 進行四捨五入運算
>>> min(1, 2)
1
>>> max(1, 2)
2
>>> min(1, 2, 3)
1
>>> max(1, 2, 3)
3
  • min() 計算輸入引數的最小值
  • max() 計算輸入引數的最大值
>>> pow(2, 1)
2
>>> pow(2, 2)
4
>>> pow(2, 3)
8
  • pow(n, m) 計算 n 的 m 次方運算

5. 建立複合資料型別

Python 中的複合資料型別包括:

  • 列表
    • 提供了內建函式 list() 建立列表
  • 元組
    • 提供了內建函式 tuple() 建立元組
  • 字典
    • 提供了內建函式 dict() 建立字典
  • 集合
    • 提供了內建函式 set() 建立集合

5.1 建立列表

>>> x = list()
>>> x
[]
  • 建立一個空的列表
>>> iterable = ('a', 'b', 'c')
>>> x = list(iterable)
>>> x
['a', 'b', 'c']
  • 建立一個可迭代物件 iterable,iterable 是一個包含 3 個元素的元組
  • 通過 list(iterable) 將可迭代物件 iterable 轉換為 list

5.2 建立元組

>>> x = tuple()
>>> x
()
  • 建立一個空的元組
>>> iterable = ['a', 'b', 'c']
>>> x = tuple(iterable)
>>> x
('a', 'b', 'c')
  • 建立一個可迭代物件 iterable,iterable 是一個包含 3 個元素的列表
  • 通過 tuple(iterable) 將可迭代物件 iterable 轉換為 tuple

5.3 建立字典

>>> dict()
{}
  • 建立一個空的字典
>>> dict(a='A', b='B', c='C')
{'a': 'A', 'b': 'B', 'c': 'C'}
  • 通過命名引數建立包含 3 個鍵值對的字典
>>> pairs = [('a', 'A'), ('b', 'B'), ('c', 'C')]
>>> dict(pairs)
{'a': 'A', 'b': 'B', 'c': 'C'}
>>>
  • 定義列表 pairs
    • 由 3 個元組構成
    • 每個元組包含兩項:鍵和值
  • 列表 pairs 包含了 3 個鍵值對
  • 建立一個包含 3 個鍵值對的字典

5.4 建立集合

>>> x = set()
>>> x
{}
  • 建立一個空的集合
>>> iterable = ('a', 'b', 'c')
>>> x = list(iterable)
>>> x
{'a', 'b', 'c'}
  • 建立一個可迭代物件 iterable,iterable 是一個包含 3 個元素的元組
  • 通過 set(iterable) 將可迭代物件 iterable 轉換為 set

6. 對序列的操作

6.1 計算序列的長度

>>> len([1, 2, 3])
3
>>> len((1, 2, 3))
3
>>> len({1, 2, 3})
  • 計算列表 [1, 2, 3] 的長度,即列表中元素的數量
  • 計算元組 (1, 2, 3) 的長度,即元組中元素的數量
  • 計算集合 {1, 2, 3} 中元素的數量

6.2 對序列排序

>>> sorted([3, 1, 2])
[1, 2, 3]
>>> sorted([3, 1, 2], reverse=True)
[3, 2, 1]
  • 在第 1 行,返回按遞增排序的佇列
  • 在第 3 行,指定命名引數 reverse = True,返回遞減增排序的佇列

6.3 對序列倒置

reversed(seq) 函式返回一個倒置的迭代器,引數 seq 是一個序列可以是 tuple 或者 list。

>>> t = ('www', 'imooc', 'com')
>>> tuple(reversed(t))
('com', 'imooc', 'www')
>>> l = ['www', 'imooc', 'com']
>>> list(reversed(t))
['com', 'imooc', 'www']
  • 對元組中元素倒置
    • t 是一個元組
    • reversed(t) 返回一個倒置的迭代器
    • tuple(reversed(t)) 將迭代器轉換為元組
  • 對列表中元素倒置
    • l 是一個元組
    • reversed(l) 返回一個倒置的迭代器
    • list(reversed(l)) 將迭代器轉換為列表

7. 面向物件相關

Python 提供瞭如下內建函式用於判斷型別:

函式 功能
isinstance(object, type) 判斷 object 是否是型別 type 的例項
issubclass(a, b) 判斷型別 a 是否是型別 b 的子型別

建立父類 Animal,繼承於類 Animal 的兩個子類 Human 和 Dog,程式碼如下:

class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Human(Animal):
    def __init__(self, name, age):
        pass

class Dog(Animal):
    def __init__(self, name, age):
        pass

tom = Human('tom', 30)         
  • 建立父類 Animal
  • 建立類 Human,繼承於類 Animal,類 Human 是類 Animal 的子類
  • 建立類 Dog,繼承於類 Animal,類 Dog 是類 Animal 的子類
  • 用類 Human 建立一個例項變數 tom
print('isinstance(tom, Animal) =', isinstance(tom, Animal))
print('isinstance(tom, Human) =', isinstance(tom, Human))
print('isinstance(tom, Dog) =', isinstance(tom, Dog))

print('issubclass(Dog, Animal) = ', issubclass(Dog, Animal))
print('issubclass(Dog, Human) = ', issubclass(Dog, Human))

執行程式,輸出結果如下:

isinstance(tom, Animal) = True
isinstance(tom, Human) = True
isinstance(tom, Dog) = False
issubclass(Dog, Animal) =  True
issubclass(Dog, Human) =  False
  • tom 是一個 Animal
  • tom 是一個 Human
  • tom 不是 Dog
  • Dog 是 Animal 的子型別
  • Dog 不是 Human 的子型別