轉(zhuǎn):[Python內(nèi)置函數(shù)詳解——總結(jié)篇]

Python內(nèi)置函數(shù)詳解——總結(jié)篇

** 引 言**

國慶期間下定決心打算學(xué)習(xí)Python氯质,于是下載安裝了開發(fā)環(huán)境勤晚。然后問題就來了,怎么開始呢烹俗?糾結(jié)一番降允,還是從官方幫助文檔開始吧恩闻。可是全是英文啊拟糕,英語渣怎么破判呕?那就邊翻譯邊看邊實踐著做吧(順便吐槽下百度翻譯,同樣的語句百度翻譯出來的結(jié)果和谷歌翻譯出來的結(jié)果差的不是一丟丟)送滞。鑒于以往學(xué)習(xí)語言的經(jīng)歷侠草,怕自己又向之前一樣學(xué)了段時間之后又不了了之,也為了記錄下學(xué)習(xí)過程的自己的一些理解和體會犁嗅,所以硬著頭皮決定開始了這個系列——Python內(nèi)置函數(shù)詳解边涕。我知道可能技術(shù)含量不好,可能其中還有些錯誤褂微,但是人呢功蜓,總要有所堅持,才能有所收獲吧宠蚂。
2個多月來式撼,將3.5版本中的68個內(nèi)置函數(shù),按順序逐個進行了自認(rèn)為詳細的解析求厕,現(xiàn)在是時候進行個總結(jié)了著隆。為了方便記憶,將這些內(nèi)置函數(shù)進行了如下分類:
[數(shù)學(xué)運算(7個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p1)

[類型轉(zhuǎn)換(24個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p2)

[序列操作(8個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p3)

[對象操作(7個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p4)

[反射操作(8個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p5)

[變量操作(2個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p6)

[交互操作(2個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p7)

[文件操作(1個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p8)

[編譯執(zhí)行(4個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p9)

[裝飾器(3個)](http://www.cnblogs.com/sesshoumaru/p/6140987.html#p10)

** 數(shù)學(xué)運算**

abs:求數(shù)值的絕對值>>> abs(-2)2

[divmod:返回兩個數(shù)值的商和余數(shù)]
[max:返回可迭代對象中的元素中的最大值或者所有參數(shù)的最大值]

max(1,2,3) # 傳入3個參數(shù) 取3個中較大者3>>> max('1234') # 傳入1個可迭代對象呀癣,取其最大元素值'4'
max(-1,0) # 數(shù)值默認(rèn)去數(shù)值較大者0
max(-1,0,key = abs) # 傳入了求絕對值函數(shù)美浦,則參數(shù)都會進行求絕對值后再取較大者-1

[min:返回可迭代對象中的元素中的最小值或者所有參數(shù)的最小值]

min(1,2,3) # 傳入3個參數(shù) 取3個中較小者1
min('1234') # 傳入1個可迭代對象,取其最小元素值'1'
min(-1,-2) # 數(shù)值默認(rèn)去數(shù)值較小者-2>>> min(-1,-2,key = abs) # 傳入了求絕對值函數(shù)项栏,則參數(shù)都會進行求絕對值后再取較小者-1

[pow:返回兩個數(shù)值的冪運算值或其與指定整數(shù)的模值]

pow(2,3)
2**3
pow(2,3,5)
pow(2,3)%5

[round:對浮點數(shù)進行四舍五入求值]

round(1.1314926,1)1.1
round(1.1314926,5)1.13149

[sum:對元素類型是數(shù)值的可迭代對象中的每個元素求和
傳入可迭代對象

sum((1,2,3,4))10# 元素類型必須是數(shù)值型
sum((1.5,2.5,3.5,4.5))12.0
sum((1,2,3,4),-10)0

** 類型轉(zhuǎn)換**

[bool:根據(jù)傳入的參數(shù)的邏輯值創(chuàng)建一個新的布爾值]

bool() #未傳入?yún)?shù)False
bool(0) #數(shù)值0浦辨、空序列等值為False
bool(1)True

[int:根據(jù)傳入的參數(shù)創(chuàng)建一個新的整數(shù)]

int() #不傳入?yún)?shù)時,得到結(jié)果0沼沈。0
int(3)3>>> int(3.6)3

float:根據(jù)傳入的參數(shù)創(chuàng)建一個新的浮點數(shù)>>> float() #不提供參數(shù)的時候流酬,返回0.00.0>>> float(3)3.0>>> float('3')3.0

complex:根據(jù)傳入?yún)?shù)創(chuàng)建一個新的復(fù)數(shù)>>> complex() #當(dāng)兩個參數(shù)都不提供時,返回復(fù)數(shù) 0j列另。0j>>> complex('1+2j') #傳入字符串創(chuàng)建復(fù)數(shù)(1+2j)>>> complex(1,2) #傳入數(shù)值創(chuàng)建復(fù)數(shù)(1+2j)

str:返回一個對象的字符串表現(xiàn)形式(給用戶)

復(fù)制代碼

str()''>>> str(None)'None'>>> str('abc')'abc'>>> str(123)'123'


復(fù)制代碼

bytearray:根據(jù)傳入的參數(shù)創(chuàng)建一個新的字節(jié)數(shù)組>>> bytearray('中文','utf-8')bytearray(b'\xe4\xb8\xad\xe6\x96\x87')

bytes:根據(jù)傳入的參數(shù)創(chuàng)建一個新的不可變字節(jié)數(shù)組>>> bytes('中文','utf-8')b'\xe4\xb8\xad\xe6\x96\x87'

memoryview:根據(jù)傳入的參數(shù)創(chuàng)建一個新的內(nèi)存查看對象>>> v = memoryview(b'abcefg')>>> v[1]98>>> v[-1]103

ord:返回Unicode字符對應(yīng)的整數(shù)>>> ord('a')97

chr:返回整數(shù)所對應(yīng)的Unicode字符>>> chr(97) #參數(shù)類型為整數(shù)'a'

bin:將整數(shù)轉(zhuǎn)換成2進制字符串>>> bin(3) '0b11'

oct:將整數(shù)轉(zhuǎn)化成8進制數(shù)字符串>>> oct(10)'0o12'

hex:將整數(shù)轉(zhuǎn)換成16進制字符串>>> hex(15)'0xf'

tuple:根據(jù)傳入的參數(shù)創(chuàng)建一個新的元組>>> tuple() #不傳入?yún)?shù)康吵,創(chuàng)建空元組()>>> tuple('121') #傳入可迭代對象。使用其元素創(chuàng)建新的元組('1', '2', '1')

list:根據(jù)傳入的參數(shù)創(chuàng)建一個新的列表>>>list() # 不傳入?yún)?shù)访递,創(chuàng)建空列表[] >>> list('abcd') # 傳入可迭代對象晦嵌,使用其元素創(chuàng)建新的列表['a', 'b', 'c', 'd']

dict:根據(jù)傳入的參數(shù)創(chuàng)建一個新的字典

復(fù)制代碼

dict() # 不傳入任何參數(shù)時,返回空字典拷姿。{}>>> dict(a = 1,b = 2) # 可以傳入鍵值對創(chuàng)建字典惭载。{'b': 2, 'a': 1}>>> dict(zip(['a','b'],[1,2])) # 可以傳入映射函數(shù)創(chuàng)建字典。{'b': 2, 'a': 1}>>> dict((('a',1),('b',2))) # 可以傳入可迭代對象創(chuàng)建字典响巢。{'b': 2, 'a': 1}


復(fù)制代碼

set:根據(jù)傳入的參數(shù)創(chuàng)建一個新的集合>>>set() # 不傳入?yún)?shù)描滔,創(chuàng)建空集合set()>>> a = set(range(10)) # 傳入可迭代對象,創(chuàng)建集合>>> a{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

frozenset:根據(jù)傳入的參數(shù)創(chuàng)建一個新的不可變集合>>> a = frozenset(range(10))>>> afrozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

enumerate:根據(jù)可迭代對象創(chuàng)建枚舉對象>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']>>> list(enumerate(seasons))[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]>>> list(enumerate(seasons, start=1)) #指定起始值[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

range:根據(jù)傳入的參數(shù)創(chuàng)建一個新的range對象

復(fù)制代碼

a = range(10)>>> b = range(1,10)>>> c = range(1,10,3)>>> a,b,c # 分別輸出a,b,c(range(0, 10), range(1, 10), range(1, 10, 3))>>> list(a),list(b),list(c) # 分別輸出a,b,c的元素([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7])>>>


復(fù)制代碼

iter:根據(jù)傳入的參數(shù)創(chuàng)建一個新的可迭代對象

復(fù)制代碼

a = iter('abcd') #字符串序列>>> a<str_iterator object at 0x03FB4FB0>>>> next(a)'a'>>> next(a)'b'>>> next(a)'c'>>> next(a)'d'>>> next(a)Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> next(a)StopIteration


復(fù)制代碼

slice:根據(jù)傳入的參數(shù)創(chuàng)建一個新的切片對象

復(fù)制代碼

c1 = slice(5) # 定義c1>>> c1slice(None, 5, None)>>> c2 = slice(2,5) # 定義c2>>> c2slice(2, 5, None)>>> c3 = slice(1,10,3) # 定義c3>>> c3slice(1, 10, 3)


復(fù)制代碼

super:根據(jù)傳入的參數(shù)創(chuàng)建一個新的子類和父類關(guān)系的代理對象

復(fù)制代碼

定義父類A>>> class A(object): def init(self): print('A.init')#定義子類B踪古,繼承A>>> class B(A): def init(self): print('B.init') super().init()#super調(diào)用父類方法>>> b = B()B.__init__A.init

復(fù)制代碼

object:創(chuàng)建一個新的object對象>>> a = object()>>> a.name = 'kim' # 不能設(shè)置屬性Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> a.name = 'kim'AttributeError: 'object' object has no attribute 'name'

** 序列操作**

all:判斷可迭代對象的每個元素是否都為True值

復(fù)制代碼

all([1,2]) #列表中每個元素邏輯值均為True含长,返回TrueTrue>>> all([0,1,2]) #列表中0的邏輯值為False券腔,返回FalseFalse>>> all(()) #空元組True>>> all({}) #空字典True


復(fù)制代碼

any:判斷可迭代對象的元素是否有為True值的元素

復(fù)制代碼

any([0,1,2]) #列表元素有一個為True,則返回TrueTrue>>> any([0,0]) #列表元素全部為False拘泞,則返回FalseFalse>>> any([]) #空列表False>>> any({}) #空字典False


復(fù)制代碼

filter:使用指定方法過濾可迭代對象的元素

復(fù)制代碼

a = list(range(1,10)) #定義序列>>> a[1, 2, 3, 4, 5, 6, 7, 8, 9]>>> def if_odd(x): #定義奇數(shù)判斷函數(shù) return x%2==1>>> list(filter(if_odd,a)) #篩選序列中的奇數(shù)[1, 3, 5, 7, 9]
", line 1, in <module> a.name = 'kim'AttributeError: 'object' object has no attribute 'name'



** 序列操作**

all:判斷可迭代對象的每個元素是否都為True值

復(fù)制代碼

>>> all([1,2]) #列表中每個元素邏輯值均為True纷纫,返回TrueTrue>>> all([0,1,2]) #列表中0的邏輯值為False,返回FalseFalse>>> all(()) #空元組True>>> all({}) #空字典True
復(fù)制代碼


any:判斷可迭代對象的元素是否有為True值的元素
復(fù)制代碼

>>> any([0,1,2]) #列表元素有一個為True陪腌,則返回TrueTrue>>> any([0,0]) #列表元素全部為False辱魁,則返回FalseFalse>>> any([]) #空列表False>>> any({}) #空字典False
復(fù)制代碼


filter:使用指定方法過濾可迭代對象的元素
復(fù)制代碼

>>> a = list(range(1,10)) #定義序列>>> a[1, 2, 3, 4, 5, 6, 7, 8, 9]>>> def if_odd(x): #定義奇數(shù)判斷函數(shù) return x%2==1>>> list(filter(if_odd,a)) #篩選序列中的奇數(shù)[1, 3, 5, 7, 9]
復(fù)制代碼

map:使用指定方法去作用傳入的每個可迭代對象的元素,生成新的可迭代對象>>> a = map(ord,'abcd')>>> a<map object at 0x03994E50>>>> list(a)[97, 98, 99, 100]

next:返回可迭代對象中的下一個元素值

復(fù)制代碼

a = iter('abcd')>>> next(a)'a'>>> next(a)'b'>>> next(a)'c'>>> next(a)'d'>>> next(a)Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> next(a)StopIteration#傳入default參數(shù)后诗鸭,如果可迭代對象還有元素沒有返回染簇,則依次返回其元素值,如果所有元素已經(jīng)返回强岸,則返回default指定的默認(rèn)值而不拋出StopIteration 異常>>> next(a,'e')'e'>>> next(a,'e')'e'

any([0,0]) #列表元素全部為False锻弓,則返回FalseFalse>>> any([]) #空列表False>>> any({}) #空字典False

復(fù)制代碼


filter:使用指定方法過濾可迭代對象的元素
復(fù)制代碼

>>> a = list(range(1,10)) #定義序列>>> a[1, 2, 3, 4, 5, 6, 7, 8, 9]>>> def if_odd(x): #定義奇數(shù)判斷函數(shù) return x%2==1>>> list(filter(if_odd,a)) #篩選序列中的奇數(shù)[1, 3, 5, 7, 9]
復(fù)制代碼


map:使用指定方法去作用傳入的每個可迭代對象的元素,生成新的可迭代對象>>> a = map(ord,'abcd')>>> a<map object at 0x03994E50>>>> list(a)[97, 98, 99, 100]

next:返回可迭代對象中的下一個元素值
復(fù)制代碼

>>> a = iter('abcd')>>> next(a)'a'>>> next(a)'b'>>> next(a)'c'>>> next(a)'d'>>> next(a)Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> next(a)StopIteration#傳入default參數(shù)后蝌箍,如果可迭代對象還有元素沒有返回弥咪,則依次返回其元素值,如果所有元素已經(jīng)返回十绑,則返回default指定的默認(rèn)值而不拋出StopIteration 異常>>> next(a,'e')'e'>>> next(a,'e')'e'
復(fù)制代碼

reversed:反轉(zhuǎn)序列生成新的可迭代對象>>> a = reversed(range(10)) # 傳入range對象>>> a # 類型變成迭代器<range_iterator object at 0x035634E8>>>> list(a)[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

sorted:對可迭代對象進行排序聚至,返回一個新的列表

復(fù)制代碼

a = ['a','b','d','c','B','A']>>> a['a', 'b', 'd', 'c', 'B', 'A']>>> sorted(a) # 默認(rèn)按字符ascii碼排序['A', 'B', 'a', 'b', 'c', 'd']>>> sorted(a,key = str.lower) # 轉(zhuǎn)換成小寫后再排序,'a'和'A'值一樣本橙,'b'和'B'值一樣['a', 'A', 'b', 'B', 'c', 'd']


復(fù)制代碼

zip:聚合傳入的每個迭代器中相同位置的元素扳躬,返回一個新的元組類型迭代器>>> x = [1,2,3] #長度3>>> y = [4,5,6,7,8] #長度5>>> list(zip(x,y)) # 取最小長度3[(1, 4), (2, 5), (3, 6)]

** 對象操作**

help:返回對象的幫助信息

復(fù)制代碼

help(str) Help on class str in module builtins:class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.str() (if defined) | or repr(object). | encoding defaults to sys.getdefaultencoding(). | errors defaults to 'strict'. | | Methods defined here: | | add(self, value, /) | Return self+value. | ***************************
a = ['a','b','d','c','B','A']>>> a['a', 'b', 'd', 'c', 'B', 'A']>>> sorted(a) # 默認(rèn)按字符ascii碼排序['A', 'B', 'a', 'b', 'c', 'd']>>> sorted(a,key = str.lower) # 轉(zhuǎn)換成小寫后再排序,'a'和'A'值一樣甚亭,'b'和'B'值一樣['a', 'A', 'b', 'B', 'c', 'd']

復(fù)制代碼


zip:聚合傳入的每個迭代器中相同位置的元素贷币,返回一個新的元組類型迭代器>>> x = [1,2,3] #長度3>>> y = [4,5,6,7,8] #長度5>>> list(zip(x,y)) # 取最小長度3[(1, 4), (2, 5), (3, 6)]


** 對象操作**

help:返回對象的幫助信息
復(fù)制代碼

>>> help(str) Help on class str in module builtins:class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.str() (if defined) | or repr(object). | encoding defaults to sys.getdefaultencoding(). | errors defaults to 'strict'. | | Methods defined here: | | add(self, value, /) | Return self+value. | ***************************
復(fù)制代碼

dir:返回對象或者當(dāng)前作用域內(nèi)的屬性列表

復(fù)制代碼

import math>>> math<module 'math' (built-in)>>>> dir(math)['doc', 'loader', 'name', 'package', 'spec', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

復(fù)制代碼

id:返回對象的唯一標(biāo)識符>>> a = 'some text'>>> id(a)69228568

hash:獲取對象的哈希值>>> hash('good good study')1032709256

type:返回對象的類型,或者根據(jù)傳入的參數(shù)創(chuàng)建一個新的類型

復(fù)制代碼

type(1) # 返回對象的類型<class 'int'>#使用type函數(shù)創(chuàng)建類型D亏狰,含有屬性InfoD>>> D = type('D',(A,B),dict(InfoD='some thing defined in D'))>>> d = D()>>> d.InfoD 'some thing defined in D'


復(fù)制代碼

len:返回對象的長度

復(fù)制代碼

len('abcd') # 字符串>>> len(bytes('abcd','utf-8')) # 字節(jié)數(shù)組>>> len((1,2,3,4)) # 元組>>> len([1,2,3,4]) # 列表>>> len(range(1,5)) # range對象>>> len({'a':1,'b':2,'c':3,'d':4}) # 字典>>> len({'a','b','c','d'}) # 集合>>> len(frozenset('abcd')) #不可變集合


復(fù)制代碼

ascii:返回對象的可打印表字符串表現(xiàn)方式

復(fù)制代碼

ascii(1)'1'>>> ascii('&')"'&'">>> ascii(9000000)'9000000'>>> ascii('中文') #非ascii字符"'\u4e2d\u6587'"


復(fù)制代碼

format:格式化顯示值

復(fù)制代碼

字符串可以提供的參數(shù) 's' None>>> format('some string','s')'some string'>>> format('some string')'some string'#整形數(shù)值可以提供的參數(shù)有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None>>> format(3,'b') #轉(zhuǎn)換成二進制'11'>>> format(97,'c') #轉(zhuǎn)換unicode成字符'a'>>> format(11,'d') #轉(zhuǎn)換成10進制'11'>>> format(11,'o') #轉(zhuǎn)換成8進制'13'>>> format(11,'x') #轉(zhuǎn)換成16進制 小寫字母表示'b'>>> format(11,'X') #轉(zhuǎn)換成16進制 大寫字母表示'B'>>> format(11,'n') #和d一樣'11'>>> format(11) #默認(rèn)和d一樣'11'#浮點數(shù)可以提供的參數(shù)有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None>>> format(314159267,'e') #科學(xué)計數(shù)法役纹,默認(rèn)保留6位小數(shù)'3.141593e+08'>>> format(314159267,'0.2e') #科學(xué)計數(shù)法,指定保留2位小數(shù)'3.14e+08'>>> format(314159267,'0.2E') #科學(xué)計數(shù)法暇唾,指定保留2位小數(shù)促脉,采用大寫E表示'3.14E+08'>>> format(314159267,'f') #小數(shù)點計數(shù)法够挂,默認(rèn)保留6位小數(shù)'314159267.000000'>>> format(3.14159267000,'f') #小數(shù)點計數(shù)法枯冈,默認(rèn)保留6位小數(shù)'3.141593'>>> format(3.14159267000,'0.8f') #小數(shù)點計數(shù)法,指定保留8位小數(shù)'3.14159267'>>> format(3.14159267000,'0.10f') #小數(shù)點計數(shù)法探熔,指定保留10位小數(shù)'3.1415926700'>>> format(3.14e+1000000,'F') #小數(shù)點計數(shù)法,無窮大轉(zhuǎn)換成大小字母'INF'#g的格式化比較特殊,假設(shè)p為格式中指定的保留小數(shù)位數(shù)蔫浆,先嘗試采用科學(xué)計數(shù)法格式化橡卤,得到冪指數(shù)exp颅悉,如果-4<=exp<p枝缔,則采用小數(shù)計數(shù)法赊舶,并保留p-1-exp位小數(shù)锄码,否則按小數(shù)計數(shù)法計數(shù)滋捶,并按p-1保留小數(shù)位數(shù)>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立垮衷,按科學(xué)計數(shù)法計數(shù)顽分,保留0位小數(shù)點'3e-05'>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立绊寻,按科學(xué)計數(shù)法計數(shù)花墩,保留1位小數(shù)點'3.1e-05'>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立悬秉,按科學(xué)計數(shù)法計數(shù),保留2位小數(shù)點'3.14e-05'>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立冰蘑,按科學(xué)計數(shù)法計數(shù)和泌,保留0位小數(shù)點,E使用大寫'3.14E-05'>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立祠肥,按小數(shù)計數(shù)法計數(shù)武氓,保留0位小數(shù)點'3'>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數(shù)計數(shù)法計數(shù)仇箱,保留1位小數(shù)點'3.1'>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立县恕,按小數(shù)計數(shù)法計數(shù),保留2位小數(shù)點'3.14'>>> format(0.00003141566,'.1n') #和g相同'3e-05'>>> format(0.00003141566,'.3n') #和g相同'3.14e-05'>>> format(0.00003141566) #和g相同'3.141566e-05'

復(fù)制代碼

vars:返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典剂桥,或者返回對象的屬性列表

復(fù)制代碼

作用于類實例>>> class A(object): pass>>> a.dict{}>>> vars(a){}>>> a.name = 'Kim'>>> a.dict{'name': 'Kim'}>>> vars(a){'name': 'Kim'}

復(fù)制代碼

** 反射操作**

import:動態(tài)導(dǎo)入模塊index = import('index')index.sayHello()

isinstance:判斷對象是否是類或者類型元組中任意類元素的實例>>> isinstance(1,int)True>>> isinstance(1,str)False>>> isinstance(1,(int,str))True

issubclass:判斷類是否是另外一個類或者類型元組中任意類元素的子類

復(fù)制代碼

issubclass(bool,int)True>>> issubclass(bool,str)False>>> issubclass(bool,(str,int))True


復(fù)制代碼

hasattr:檢查對象是否含有屬性

復(fù)制代碼

定義類A>>> class Student: def init(self,name): self.name = name >>> s = Student('Aim')>>> hasattr(s,'name') #a含有name屬性True>>> hasattr(s,'age') #a不含有age屬性False

復(fù)制代碼

getattr:獲取對象的屬性值

復(fù)制代碼

定義類Student>>> class Student: def init(self,name): self.name = name>>> getattr(s,'name') #存在屬性name'Aim'>>> getattr(s,'age',6) #不存在屬性age忠烛,但提供了默認(rèn)值,返回默認(rèn)值>>> getattr(s,'age') #不存在屬性age权逗,未提供默認(rèn)值美尸,調(diào)用報錯Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> getattr(s,'age')AttributeError: 'Stduent' object has no attribute 'age'

復(fù)制代碼

setattr:設(shè)置對象的屬性值

復(fù)制代碼

class Student: def init(self,name): self.name = name >>> a = Student('Kim')>>> a.name'Kim'>>> setattr(a,'name','Bob')>>> a.name'Bob'

復(fù)制代碼

delattr:刪除對象的屬性

復(fù)制代碼

定義類A>>> class A: def init(self,name): self.name = name def sayHello(self): print('hello',self.name)#測試屬性和方法>>> a.name'小麥'>>> a.sayHello()hello 小麥#刪除屬性>>> delattr(a,'name')>>> a.nameTraceback (most recent call last): File "<pyshell#47>", line 1, in <module> a.nameAttributeError: 'A' object has no attribute 'name'

復(fù)制代碼

callable:檢測對象是否可被調(diào)用

復(fù)制代碼

class B: #定義類B def call(self): print('instances are callable now.') >>> callable(B) #類B是可調(diào)用對象True>>> b = B() #調(diào)用類B>>> callable(b) #實例b是可調(diào)用對象True>>> b() #調(diào)用實例b成功instances are callable now.

復(fù)制代碼

** 變量操作**

globals:返回當(dāng)前作用域內(nèi)的全局變量和其值組成的字典

復(fù)制代碼

globals(){'spec': None, 'package': None, 'builtins': <module 'builtins' (built-in)>, 'name': 'main', 'doc': None, 'loader': <class '_frozen_importlib.BuiltinImporter'>}>>> a = 1>>> globals() #多了一個a{'spec': None, 'package': None, 'builtins': <module 'builtins' (built-in)>, 'a': 1, 'name': 'main', 'doc': None, 'loader': <class '_frozen_importlib.BuiltinImporter'>}

復(fù)制代碼

locals:返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典

復(fù)制代碼

def f(): print('before define a ') print(locals()) #作用域內(nèi)無變量 a = 1 print('after define a') print(locals()) #作用域內(nèi)有一個a變量,值為1 >>> f<function f at 0x03D40588>>>> f()before define a {} after define a{'a': 1}


復(fù)制代碼

** 交互操作**

print:向標(biāo)準(zhǔn)輸出對象打印輸出>>> print(1,2,3)1 2 3>>> print(1,2,3,sep = '+')1+2+3>>> print(1,2,3,sep = '+',end = '=?')1+2+3=?

input:讀取用戶輸入值>>> s = input('please input your name:')please input your name:Ain>>> s'Ain'

** 文件操作**

open:使用指定的模式和編碼打開文件斟薇,返回文件讀寫對象# t為文本讀寫师坎,b為二進制讀寫>>> a = open('test.txt','rt')>>> a.read()'some text'>>> a.close()

** 編譯執(zhí)行**

compile:將字符串編譯為代碼或者AST對象,使之能夠通過exec語句來執(zhí)行或者eval進行求值

復(fù)制代碼

流程語句使用exec>>> code1 = 'for i in range(0,10): print (i)'>>> compile1 = compile(code1,'','exec')>>> exec (compile1)0123456789>>> #簡單求值表達式用eval>>> code2 = '1 + 2 + 3 + 4'>>> compile2 = compile(code2,'','eval')>>> eval(compile2)10

復(fù)制代碼

eval:執(zhí)行動態(tài)表達式求值>>> eval('1+2+3+4')10

exec:執(zhí)行動態(tài)語句塊>>> exec('a=1+2') #執(zhí)行語句>>> a3

repr:返回一個對象的字符串表現(xiàn)形式(給解釋器)>>> a = 'some text'>>> str(a)'some text'>>> repr(a)"'some text'"

** 裝飾器**

property:標(biāo)示屬性的裝飾器

復(fù)制代碼

class C: def init(self): self._name = '' @property def name(self): """i'm the 'name' property.""" return self._name @name.setter def name(self,value): if value is None: raise RuntimeError('name can not be None') else: self._name = value >>> c = C()>>> c.name # 訪問屬性''>>> c.name = None # 設(shè)置屬性時進行驗證Traceback (most recent call last): File "<pyshell#84>", line 1, in <module> c.name = None File "<pyshell#81>", line 11, in name raise RuntimeError('name can not be None')RuntimeError: name can not be None>>> c.name = 'Kim' # 設(shè)置屬性>>> c.name # 訪問屬性'Kim'>>> del c.name # 刪除屬性堪滨,不提供deleter則不能刪除Traceback (most recent call last): File "<pyshell#87>", line 1, in <module> del c.nameAttributeError: can't delete attribute>>> c.name'Kim'

復(fù)制代碼

classmethod:標(biāo)示方法為類方法的裝飾器

復(fù)制代碼

class C: @classmethod def f(cls,arg1): print(cls) print(arg1) >>> C.f('類對象調(diào)用類方法')<class 'main.C'>類對象調(diào)用類方法>>> c = C()>>> c.f('類實例對象調(diào)用類方法')<class 'main.C'>類實例對象調(diào)用類方法

復(fù)制代碼

staticmethod:標(biāo)示方法為靜態(tài)方法的裝飾器

復(fù)制代碼

使用裝飾器定義靜態(tài)方法>>> class Student(object): def init(self,name): self.name = name @staticmethod def sayHello(lang): print(lang) if lang == 'en': print('Welcome!') else: print('你好胯陋!') >>> Student.sayHello('en') #類調(diào)用,'en'傳給了lang參數(shù)enWelcome!>>> b = Student('Kim')>>> b.sayHello('zh') #類實例對象調(diào)用,'zh'傳給了lang參數(shù)zh你好

復(fù)制代碼

作者:〖十月狐貍〗
出處:http://www.cnblogs.com/sesshoumaru/
歡迎任何形式的轉(zhuǎn)載,但請務(wù)必注明出處。
本人水平有限惶岭,如果文章和代碼有表述不當(dāng)之處寿弱,還請不吝賜教。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末按灶,一起剝皮案震驚了整個濱河市症革,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌鸯旁,老刑警劉巖噪矛,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異铺罢,居然都是意外死亡艇挨,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門韭赘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來缩滨,“玉大人,你說我怎么就攤上這事泉瞻÷雎” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵袖牙,是天一觀的道長侧巨。 經(jīng)常有香客問我,道長鞭达,這世上最難降的妖魔是什么司忱? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮畴蹭,結(jié)果婚禮上坦仍,老公的妹妹穿的比我還像新娘。我一直安慰自己叨襟,他們只是感情好繁扎,可當(dāng)我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著芹啥,像睡著了一般锻离。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上墓怀,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天汽纠,我揣著相機與錄音,去河邊找鬼傀履。 笑死虱朵,一個胖子當(dāng)著我的面吹牛莉炉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播碴犬,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼絮宁,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了服协?” 一聲冷哼從身側(cè)響起绍昂,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎偿荷,沒想到半個月后窘游,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡跳纳,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年忍饰,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片寺庄。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡艾蓝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出斗塘,到底是詐尸還是另有隱情赢织,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布逛拱,位于F島的核電站敌厘,受9級特大地震影響台猴,放射性物質(zhì)發(fā)生泄漏朽合。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一饱狂、第九天 我趴在偏房一處隱蔽的房頂上張望曹步。 院中可真熱鬧,春花似錦休讳、人聲如沸讲婚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽筹麸。三九已至,卻和暖如春雏婶,著一層夾襖步出監(jiān)牢的瞬間物赶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工留晚, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留酵紫,地道東北人。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像奖地,于是被迫代替她去往敵國和親橄唬。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 《裕語言》速成開發(fā)手冊3.0 官方用戶交流:iApp開發(fā)交流(1) 239547050iApp開發(fā)交流(2) 10...
    葉染柒丶閱讀 26,632評論 5 19
  • 內(nèi)置函數(shù)Python解釋器內(nèi)置了許多功能和類型,總是可用的参歹。他們是按字母順序列在這里仰楚。 abs(x)返回一個數(shù)的絕...
    uangianlap閱讀 1,236評論 0 0
  • Python 是一種相當(dāng)高級的語言,通過 Python 解釋器把符合語法的程序代碼轉(zhuǎn)換成 CPU 能夠執(zhí)行的機器碼...
    Python程序媛閱讀 1,902評論 0 3
  • 《ilua》速成開發(fā)手冊3.0 官方用戶交流:iApp開發(fā)交流(1) 239547050iApp開發(fā)交流(2) 1...
    葉染柒丶閱讀 10,686評論 0 11
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理犬庇,服務(wù)發(fā)現(xiàn)缸血,斷路器,智...
    卡卡羅2017閱讀 134,651評論 18 139