abs(x)
all()
用於判斷給定的可迭代參數 iterable 中的所有元素是否都為 TRUE,如果是返回 True,否則返回 False。
元素除了是 0、空、None、False 外都算 True。
all(iterable) #iterable -- 元組或列表 >>> all([1,2,0]) False >>> all([1,2,1]) True
any()
用於判斷給定的可迭代參數 iterable 是否全部為 False,則返回 False,如果有一個為 True,則返回 True。
元素除了是 0、空、FALSE 外都算 TRUE。
>>> any([1,2,0]) True >>> any([0,0]) False
ascii()
中文轉ASC碼。
>>> ascii([1,2,"測試"]) "[1, 2, '\\u6d4b\\u8bd5']"
bin()
十進制轉二進制。
bin(x)
bool()
判斷真假。
>>> bool(1) True >>> bool(0) False
bytes()
返回一個新的“bytes”對象, 是一個不可變序列。
class bytes([source[, encoding[, errors]]])
>>> bytes('abcd',encoding="utf-8")
b'abcd'
bytearray()
返回一個新的 bytes 數組。 bytearray 類是一個可變序列。改二進制字符。
bytearray([source[, encoding[, errors]]])
>>> a = bytearray('abcd',encoding="utf-8")
>>> a[0]
97
>>> a[0] = 99
>>> a
bytearray(b'cbcd')
callable()
如果參數 object 是可調用的就返回 True,否則返回 False。
>>> callable(int) True
chr()
chr() 用一個范圍在 range(256)內的(就是0~255)整數作參數,返回一個對應的字符。
>>> chr(100) 'd'
ord()
ord() 函數是 chr() 函數(對於8位的ASCII字符串)或 unichr() 函數(對於Unicode對象)的配對函數,它以一個字符(長度為1的字符串)作為參數,返回對應的 ASCII 數值,或者 Unicode 數值。
>>> ord('a')
97
@classmethod
把一個方法封裝成類方法。
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
compile()
compile() 函數將一個字符串編譯為字節代碼,用於底層編譯的。
語法:
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) 將 source 編譯成代碼或 AST 對象。代碼對象可以被 exec() 或 eval() 執行。source 可以是常規的字符串、字節字符串,或者 AST 對象。 filename 實參需要是代碼讀取的文件名 mode 實參指定了編譯代碼必須用的模式。如果 source 是語句序列,可以是 'exec';如果是單一表達式,可以是 'eval';如果是單個交互式語句,可以是 'single'。
>>> code = "for i in range(10):print(i)" >>> c = compile(code,'','exec') >>> c <code object <module> at 0x000001A23F969300, file "", line 1> >>> exec(c) 0 1 2 3 4 5 6 7 8 9
也可以是表達式。
>>> code = "1+2+3/2" >>> c = compile(code,'','eval') >>> eval(c) 4.5
exec()
exec(object[, globals[, locals]])
這個函數支持動態執行 Python 代碼。object 必須是字符串或者代碼對象。如果是字符串,那么該字符串將被解析為一系列 Python 語句並執行(除非發生語法錯誤)。 如果是代碼對象,它將被直接執行。在任何情況下,被執行的代碼都需要和文件輸入一樣是有效的
complex()
返回值為 real + imag*1j 的復數,或將字符串或數字轉換為復數。
>>> complex(1,2) (1+2j)
delattr()
delattr(object, name)
實參是一個對象和一個字符串。該字符串必須是對象的某個屬性。如果對象允許,該函數將刪除指定的屬性。
例如 delattr(x, 'foobar') 等價於 del x.foobar 。
dir()
dir() 函數不帶參數時,返回當前范圍內的變量、方法和定義的類型列表;帶參數時,返回參數的屬性、方法列表。
>>> dir(code) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
divmod()
它將兩個(非復數)數字作為實參,並在執行整數除法時返回一對商和余數。
>>> divmod(10,2) (5, 0)
enumerate
enumerate() 函數用於將一個可遍歷的數據對象(如列表、元組或字符串)組合為一個索引序列,同時列出數據和數據下標,一般用在 for 循環當中。
>>> a=['a','b','b','d','e'] >>> for i,e in enumerate(a): ... print(i,e) ... 0 a 1 b 2 b 3 d 4 e
eval()
eval() 函數用來執行一個字符串表達式,並返回表達式的值。
可以把字符串變成字典。
>>> a="{'a':'b'}"
>>> type(a)
<class 'str'>
>>> b = eval(a)
>>> type(b)
<class 'dict'>
filter()
filter(function, iterable)
用 iterable 中函數 function 返回真的那些元素,構建一個新的迭代器。iterable 可以是一個序列,一個支持迭代的容器,或一個迭代器。
>>> f = filter(lambda n:n>5,range(10)) >>> f <filter object at 0x000001A23FA31BE0> >>> for i in f: ... print(i) ... 6 7 8 9
map()
返回一個將 function 應用於 iterable 中每一項並輸出其結果的迭代器。
map(function, iterable)
>>> m = map(lambda n:n*n,range(10)) >>> for i in m: ... print(i) ... 0 1 4 9 16 25 36 49 64 81
float()
返回從數字或字符串 x 生成的浮點數。
>>> float(2) 2.0
format()
將 value 轉換為 format_spec 控制的“格式化”表示。
>>> "{}".format("hello")
'hello'
frozenset()
frozenset([iterable])
frozenset() 返回一個凍結的集合,凍結后集合不能再添加或刪除任何元素。
>>> l = [1,2,3,4]
>>> dir(l)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> frozenset(l)
frozenset({1, 2, 3, 4})
>>> x = frozenset(l)
>>> dir(x)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']
getattr()
getattr(object, name[, default])
返回對象命名屬性的值。name 必須是字符串。如果該字符串是對象的屬性之一,則返回該屬性的值。例如, getattr(x, 'foobar') 等同於 x.foobar。
globals()
以鍵值對的方式返回當前程序的所有變量。
>>> print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': "{'a':'b'}", 'code': '1+2+3/2', 'c': <code object <module> at 0x000001A23F9699C0, file "", line 1>, 'i': 81, 'e': 'e', 'b': {'a': 'b'}, 'f': <filter object at 0x000001A23FA31BE0>, 'm': <map object at 0x000001A23FA31C18>, 'l': [1, 2, 3, 4], 'x': frozenset({1, 2, 3, 4})}
hash()
返回該對象的哈希值(如果它有的話)。哈希值是整數。
>>> hash('abcs')
-5430407018906191666
help()
查看函數或模塊用途的詳細說明。
>>> help(chr)
Help on built-in function chr in module builtins:
chr(i, /)
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
hex()
將一個指定數字轉換為 16 進制數。
>>> hex(15) '0xf'
id()
獲取對象的內存地址。
>>> a="hello" >>> id(a) 2047968913928
int()
將一個字符串或數字轉換為整型。
>>> int("111")
111
input()
接受一個標准輸入數據,返回為 string 類型。
>>> str = input("Input value")
Input value hello
>>> str
' hello'
isinstance()
判斷一個對象是否是一個已知的類型。
>>>a = 2 >>> isinstance (a,int) True >>> isinstance (a,str) False
issubclass()
判斷參數 class 是否是類型參數 classinfo 的子類。
class A:
pass
class B(A):
pass
print(issubclass(B,A)) # 返回 True
iter()
用來生成迭代器。
iter(object[, sentinel])
- object -- 支持迭代的集合對象。
- sentinel -- 如果傳遞了第二個參數,則參數 object 必須是一個可調用的對象(如,函數),此時,iter 創建了一個迭代器對象,每次調用這個迭代器對象的__next__()方法時,都會調用 object。
>>>lst = [1, 2, 3] >>> for i in iter(lst): ... print(i) ... 1 2 3
len()
返回對象(字符、列表、元組等)長度或項目個數。
>>> len('avc')
3
locals()
以字典類型返回當前位置的全部局部變量。
>>> def a():
... x='aaa'
... print(locals())
...
>>> a()
{'x': 'aaa'}
list()
用於將元組或字符串轉換為列表。
>>> a = '[1,2,3,4]' >>> x = list(a) >>> x ['[', '1', ',', '2', ',', '3', ',', '4', ']']
max()
返回給定參數的最大值,參數可以為序列。
>>> max(100,1000,10) 1000
min()
返回給定參數的最小值,參數可以為序列。
>>> min('a','b','c')
'a'
memoryview()
返回給定參數的內存查看對象(Momory view)。
>>>v = memoryview(bytearray("abcefg", 'utf-8'))
>>> print(v[1])
98
>>> print(v[-1])
103
>>> print(v[1:4])
<memory at 0x10f543a08>
>>> print(v[1:4].tobytes())
b'bce'
>>>
next()
返回迭代器的下一個項目,相當於__next__()。
it = iter([1, 2, 3, 4, 5])
while True:
try:
x = next(it)
print(x)
except StopIteration:
break
object()
面向對象中的對象。
oct()
將一個整數轉換成8進制字符串
>>> oct(1) '0o1'
open()
用於打開一個文件,並返回文件對象。
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
- file: 必需,文件路徑(相對或者絕對路徑)。
- mode: 可選,文件打開模式
- buffering: 設置緩沖
- encoding: 一般使用utf8
- errors: 報錯級別
- newline: 區分換行符
- closefd: 傳入的file參數類型
- opener:
pow()
返回x的y次方的值。
>>> import math >>> math.pow(2,3) 8.0
print()
用於打印輸出。
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- objects -- 復數,表示可以一次輸出多個對象。輸出多個對象時,需要用 , 分隔。
- sep -- 用來間隔多個對象,默認值是一個空格。
- end -- 用來設定以什么結尾。默認值是換行符 \n,我們可以換成其他字符串。
- file -- 要寫入的文件對象。
- flush -- 輸出是否被緩存通常決定於 file,但如果 flush 關鍵字參數為 True,流會被強制刷新。
property()
新式類中返回屬性值。
class property([fget[, fset[, fdel[, doc]]]]) 參數 fget -- 獲取屬性值的函數 fset -- 設置屬性值的函數 fdel -- 刪除屬性值函數 doc -- 屬性描述信息
class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
range()
返回的是一個可迭代對象(類型是對象)。
>>>range(5) range(0, 5)
repr()
將對象轉化為供解釋器讀取的形式。
>>> a '[1,2,3,4]' >>> repr(a) "'[1,2,3,4]'"
reversed()
返回一個反轉的迭代器。
>>> a="admin" >>> reversed(a) <reversed object at 0x000001DCD474A6A0> >>> print(a) admin
round()
返回浮點數 x 的四舍五入值。
round( x [, n] ) >>> round(1.335,2) 1.33
set()
創建一個無序不重復元素集。
>>> x=set('test')
>>> x
{'t', 'e', 's'}
slice()
實現切片對象,主要用在切片操作函數里的參數傳遞。
setattr(object, name, value)
- object -- 對象。
- name -- 字符串,對象屬性。
- value -- 屬性值。
>>> a = range(0,20) >>> a[slice(5,10)] range(5, 10)
setattr()
對應函數 getattr(),用於設置屬性值,該屬性不一定是存在的。
setattr(object, name, value) object -- 對象。 name -- 字符串,對象屬性。 value -- 屬性值。 >>>class A(object): ... bar = 1 ... >>> a = A() >>> getattr(a, 'bar') # 獲取屬性 bar 值 1 >>> setattr(a, 'bar', 5) # 設置屬性 bar 值 >>> a.bar 5
sorted()
對所有可迭代的對象進行排序操作。
>>> a = [1,3,5,97,12,55,33] >>> x = sorted(a) >>> x [1, 3, 5, 12, 33, 55, 97]
staticmethod()
返回函數的靜態方法。
class C(object): @staticmethod def f(): print('runoob'); C.f(); # 靜態方法無需實例化 cobj = C() cobj.f() # 也可以實例化后調用 ##輸出 runoob runoob
str()
將對象轉化為文本的形式。
sum()
對系列進行求和計算。
sum(iterable[, start])
- iterable -- 可迭代對象,如:列表、元組、集合。
- start -- 指定相加的參數,如果沒有設置這個值,默認為0。
>>> a = [1,2,3] >>> sum(a) 6
super()
用於調用父類(超類)的一個方法。用於面向對象繼承。
super(type[, object-or-type])
- type -- 類。
- object-or-type -- 類,一般是 self
tuple()
將可迭代系列(如列表)轉換為元組。
tuple( iterable )
iterable -- 要轉換為元組的可迭代序列。
type()
只有第一個參數則返回對象的類型,三個參數返回新的類型對象。
type(object) type(name, bases, dict)
- name -- 類的名稱。
- bases -- 基類的元組。
- dict -- 字典,類內定義的命名空間變量。
vars()
返回對象object的屬性和屬性值的字典對象。
>>> class Test:
... a = 1
...
>>> print(vars(Test))
{'a': 1, '__module__': '__main__', '__doc__': None}
zip()
用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的對象,這樣做的好處是節約了不少的內存。
>>> a [1, 2, 3] >>> b=['a','b','c'] >>> print(zip(a,b)) <zip object at 0x000001DCD4A30108> >>> for i in zip(a,b): ... print(i) ... (1, 'a') (2, 'b') (3, 'c')
__import__()
用於動態加載類和函數 。
__import__('a') # 導入 a.py 模塊
