Python內(nèi)置函數(shù)(1)— abs()、all()雾鬼、any()萌朱、ascii()、bin()策菜、bool()晶疼、breakpoint()酒贬、bytearray()、bytes()翠霍、callable()锭吨。
Python內(nèi)置函數(shù)(2)— chr()、classmethod()寒匙、compile()零如、complex()、delattr()锄弱、dict()考蕾、dir()、divmod()会宪、enumerate()辕翰、eval()。
Python內(nèi)置函數(shù)(3)— exec()狈谊、filter()喜命、float()、format()河劝、frozenset()壁榕、getattr()、globals()赎瞎、hasattr()牌里、hash()、help()务甥。
Python內(nèi)置函數(shù)(4)— hex()牡辽、id()、input()敞临、int()态辛、isinstance()、issubclass挺尿、iter()奏黑、len()、list()编矾、locals()熟史。
Python內(nèi)置函數(shù)(5)— map()、max()窄俏、memoryview()蹂匹、min()、next()凹蜈、object()限寞、oct()忍啸、open()、ord()昆烁、pow()吊骤。
Python內(nèi)置函數(shù)(6)— print()缎岗、property()静尼、range()、repr()传泊、reversed()鼠渺、round()、set()眷细、setattr()拦盹、slice()、sorted()溪椎。
Python內(nèi)置函數(shù)(7)— staticmethod()普舆、str()、sum()校读、super()沼侣、tuple()、type()歉秫、vars()蛾洛、zip()、__import__()雁芙。
61轧膘、staticmethod()
a)描述
staticmethod 返回函數(shù)的靜態(tài)方法。
該方法不強制要求傳遞參數(shù)兔甘,如下聲明一個靜態(tài)方法:
class C(object):
@staticmethod
def f(arg1, arg2, ...):
...
以上實例聲明了靜態(tài)方法 f谎碍,從而可以實現(xiàn)實例化使用 C().f(),當(dāng)然也可以不實例化調(diào)用該方法 C.f()洞焙。
b)語法
staticmethod的語法:staticmethod(function)
c)參數(shù)
無椿浓。
d)返回值
無。
e)實例
實例1:
class C(object):
@staticmethod
def f():
print('kevin');
C.f(); # 靜態(tài)方法無需實例化
cobj = C()
cobj.f() # 也可以實例化后調(diào)用
運行結(jié)果:
kevin
kevin
實例2(staticmethod 參數(shù)要求是 Callable, 也就是說 Class 也是可以的):
class C1(object):
@staticmethod
class C2(object):
def __init__(self, val = 1):
self.val = val
def shout(self):
print("Python世界第%d!"%self.val)
tmp = C1.C2(0)
print(type(tmp)) # 輸出 : <class '__main__.C1.C2'>
tmp.shout() # 輸出 : Python世界第0!
運行結(jié)果:
<class '__main__.C1.C2'>
Python世界第0!
62闽晦、str()
a)描述
str() 函數(shù)將對象轉(zhuǎn)化為適于人閱讀的形式扳碍。
b)語法
str() 方法的語法:class str(object='')
c)參數(shù)
object:對象。
d)返回值
返回一個對象的string格式仙蛉。
e)實例
s = 'Kevin'
print("str(s):",str(s))
dict = {'kevin': 'kevin.com', 'google': 'google.com'};
print("str(dict):",str(dict))
運行結(jié)果:
str(s): Kevin
str(dict): {'kevin': 'kevin.com', 'google': 'google.com'}
63笋敞、sum()
a)描述
原文:
Return the sum of a 'start' value (default: 0) plus an iterable of numbers.
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may reject non-numeric types.
中文:
返回一個'start'值(默認(rèn)值為0)和一個可迭代的數(shù)字的總和。
當(dāng)iterable為空時荠瘪,返回初始值夯巷。
此函數(shù)專門用于數(shù)值類型赛惩,可以拒絕非數(shù)值類型。
詮釋:
sum() 方法對系列進(jìn)行求和計算趁餐。
b)語法
sum() 方法的語法:sum(iterable[, start])
c)參數(shù)
iterable:可迭代對象喷兼,如:列表、元組后雷、集合季惯。
start:指定相加的參數(shù),如果沒有設(shè)置這個值臀突,默認(rèn)為0勉抓。
d)返回值
返回計算結(jié)果。
e)實例
print("sum([0,1,2]):",sum([0,1,2]))
print("sum((2, 3, 4), 1):",sum((2, 3, 4), 1)) # 元組計算總和后再加 1
print("sum([0,1,2,3,4], 2):",sum([0,1,2,3,4], 2)) # 列表計算總和后再加 2
運行結(jié)果:
sum([0,1,2]): 3
sum((2, 3, 4), 1): 10
sum([0,1,2,3,4], 2): 12
64候学、super()
a)描述
super() 函數(shù)是用于調(diào)用父類(超類)的一個方法藕筋。
super 是用來解決多重繼承問題的,直接用類名調(diào)用父類方法在使用單繼承的時候沒問題梳码,但是如果使用多繼承隐圾,會涉及到查找順序(MRO)、重復(fù)調(diào)用(鉆石繼承)等種種問題掰茶。
MRO 就是類的方法解析順序表, 其實也就是繼承父類方法時的順序表暇藏。
b)語法
super() 方法的語法:super(type[, object-or-type])
c)參數(shù)
type:類。
object-or-type:類符匾,一般是 self
d)返回值
無叨咖。
e)實例
實例1:
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print('Parent')
def bar(self, message):
print("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
# super(FooChild,self) 首先找到 FooChild 的父類(就是類 FooParent),然后把類 FooChild 的對象轉(zhuǎn)換為類 FooParent 的對象
super(FooChild, self).__init__()
print('Child')
def bar(self, message):
super(FooChild, self).bar(message)
print('Child bar fuction')
print(self.parent)
if __name__ == '__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
運行結(jié)果:
Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.
實例2:
經(jīng)典的菱形繼承案例啊胶,BC 繼承 A甸各,然后 D 繼承 BC,創(chuàng)造一個 D 的對象焰坪。
---> B ---
A --| |--> D
---> C ---
使用 super() 可以很好地避免構(gòu)造函數(shù)被調(diào)用兩次趣倾。
class A():
def __init__(self):
print('enter A')
print('leave A')
class B(A):
def __init__(self):
print('enter B')
super().__init__()
print('leave B')
class C(A):
def __init__(self):
print('enter C')
super().__init__()
print('leave C')
class D(B, C):
def __init__(self):
print('enter D')
super().__init__()
print('leave D')
d = D()
運行結(jié)果:
enter D
enter B
enter C
enter A
leave A
leave C
leave B
leave D
實例3:
在學(xué)習(xí) Python 類的時候,總會碰見書上的類中有 init() 這樣一個函數(shù)某饰,很多同學(xué)百思不得其解儒恋,其實它就是 Python 的構(gòu)造方法。
構(gòu)造方法類似于類似 init() 這種初始化方法黔漂,來初始化新創(chuàng)建對象的狀態(tài)诫尽,在一個對象唄創(chuàng)建以后會立即調(diào)用,比如像實例化一個類:
f = FooBar()
f.init()
使用構(gòu)造方法就能讓它簡化成如下形式:
f = FooBar()
你可能還沒理解到底什么是構(gòu)造方法炬守,什么是初始化牧嫉,下面我們再來舉個例子:
class FooBar:
def __init__(self):
self.somevar = 42
>>>f = FooBar()
>>>f.somevar
我們會發(fā)現(xiàn)在初始化 FooBar 中的 somevar 的值為 42 之后,實例化直接就能夠調(diào)用 somevar 的值;如果說你沒有用構(gòu)造方法初始化值得話酣藻,就不能夠調(diào)用曹洽,明白了嗎?
在明白了構(gòu)造方法之后辽剧,我們來點進(jìn)階的問題送淆,那就是構(gòu)造方法中的初始值無法繼承的問題。
例子:
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print 'Ahahahah'
else:
print 'No thanks!'
class SongBird(Bird):
def __init__(self):
self.sound = 'Squawk'
def sing(self):
print self.song()
sb = SongBird()
sb.sing() # 能正常輸出
sb.eat() # 報錯怕轿,因為 songgird 中沒有 hungry 特性
那解決這個問題的辦法有兩種:
1偷崩、調(diào)用未綁定的超類構(gòu)造方法(多用于舊版 python 陣營)
class SongBird(Bird):
def __init__(self):
Bird.__init__(self)
self.sound = 'Squawk'
def sing(self):
print self.song()
原理:在調(diào)用了一個實例的方法時,該方法的self參數(shù)會自動綁定到實例上(稱為綁定方法)撤卢;如果直接調(diào)用類的方法(比如Bird.init)环凿,那么就沒有實例會被綁定梧兼,可以自由提供需要的self參數(shù)(未綁定方法)放吩。
2、使用super函數(shù)(只在新式類中有用)
class SongBird(Bird):
def __init__(self):
super(SongBird,self).__init__()
self.sound = 'Squawk'
def sing(self):
print self.song()
原理:它會查找所有的超類羽杰,以及超類的超類渡紫,直到找到所需的特性為止。
65考赛、tuple()
a)描述
tuple 函數(shù)將可迭代系列(如列表)轉(zhuǎn)換為元組惕澎。
b)語法
tuple 的語法:tuple( iterable )
c)參數(shù)
iterable:要轉(zhuǎn)換為元組的可迭代序列。
d)返回值
返回元組颜骤。
e)實例
實例1:
list1= ['Google', 'Taobao', 'Kevin', 'Baidu']
tuple1=tuple(list1)
print("tuple1:",tuple1)
運行結(jié)果:
tuple1: ('Google', 'Taobao', 'Kevin', 'Baidu')
實例2(tuple() 可以將字符串唧喉,列表,字典忍抽,集合轉(zhuǎn)化為元組):
a = 'www'
b = tuple(a)
print("b:",b)
c = {'www':123,'aaa':234}
d = tuple(c)
print("d:",d)
e = set('abcd')
print("e:",e)
f = tuple(e)
print("f:",f)
運行結(jié)果:
b: ('w', 'w', 'w')
d: ('www', 'aaa') # 將字段轉(zhuǎn)換為元組時八孝,只保留鍵!
e: {'a', 'b', 'd', 'c'}
f: ('a', 'b', 'd', 'c')
66鸠项、type()
type() 函數(shù)如果你只有第一個參數(shù)則返回對象的類型干跛,三個參數(shù)返回新的類型對象。
isinstance() 與 type() 區(qū)別:
type() 不會認(rèn)為子類是一種父類類型祟绊,不考慮繼承關(guān)系楼入。
isinstance() 會認(rèn)為子類是一種父類類型,考慮繼承關(guān)系牧抽。
如果要判斷兩個類型是否相同推薦使用 isinstance()嘉熊。
b)語法
type() 方法的語法:
type(object)
type(name, bases, dict)
c)參數(shù)
name:類的名稱。
bases:基類的元組扬舒。
dict:字典阐肤,類內(nèi)定義的命名空間變量。
d)返回值
一個參數(shù)返回對象類型, 三個參數(shù)呼巴,返回新的類型對象泽腮。
e)實例
實例1:
# 一個參數(shù)實例
print("type(1):",type(1))
print("type('kevin'):",type('kevin'))
print("type([2]):",type([2]))
print("type({0: 'zero'}):",type({0: 'zero'}))
x = 1
print("type(x) == int:",type(x) == int) # 判斷類型是否相等
# 三個參數(shù)
class X(object):
a = 1
X = type('X', (object,), dict(a=1)) # 產(chǎn)生一個新的類型 X
print("X:",X)
運行結(jié)果:
type(1): <class 'int'>
type('kevin'): <class 'str'>
type([2]): <class 'list'>
type({0: 'zero'}): <class 'dict'>
type(x) == int: True
X: <class '__main__.X'>
實例2:
class A:
pass
class B(A):
pass
print("isinstance(A(), A):",isinstance(A(), A))
print("type(A()) == A:",type(A()) == A)
print("isinstance(B(), A):",isinstance(B(), A))
print("type(B()) == A:",type(B()) == A)
運行結(jié)果:
isinstance(A(), A): True
type(A()) == A: True
isinstance(B(), A): True
type(B()) == A: False
67御蒲、vars()
a)描述
原文:
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__
.
中文:
vars([object]) -> dictionary
沒有參數(shù),等價于locals()诊赊。
等價于object.__dict__
厚满。
詮釋:
vars() 函數(shù)返回對象object的屬性和屬性值的字典對象。
b)語法
vars() 函數(shù)語法:vars([object])
c)參數(shù)
object:對象碧磅。
d)返回值
返回對象object的屬性和屬性值的字典對象碘箍,如果沒有參數(shù),就打印當(dāng)前調(diào)用位置的屬性和屬性值 類似 locals()鲸郊。
e)實例
print(vars())
class Kevin:
a = 1
print(vars(Kevin))
kevin = Kevin()
print(vars(kevin))
運行結(jié)果:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000022F9DE10970>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/Python_Project/Temp.py', '__cached__': None}
{'__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'Kevin' objects>, '__weakref__': <attribute '__weakref__' of 'Kevin' objects>, '__doc__': None}
{}
68丰榴、zip()
a)描述
原文:
zip(iterables) --> zip object
Return a zip object whose .__next__()
method returns a tuple where the i-th element comes from the i-th iterable argument. The .__next__()
method continues until the shortest iterable in the argument sequence is exhausted and then it raises StopIteration.
中文:
zip(iterables) --> zip object
返回一個zip對象,其.__next__()
方法返回一個元組秆撮,其中第i個元素來自第i個迭代參數(shù)四濒。.__next__()
方法將繼續(xù)執(zhí)行,直到參數(shù)序列中最短的迭代被用盡职辨,然后它將引發(fā)StopIteration盗蟆。
詮釋:
zip() 函數(shù)用于將可迭代的對象作為參數(shù),將對象中對應(yīng)的元素打包成一個個元組舒裤,然后返回由這些元組組成的對象喳资,這樣做的好處是節(jié)約了不少的內(nèi)存。
我們可以使用 list() 轉(zhuǎn)換來輸出列表腾供。
如果各個迭代器的元素個數(shù)不一致仆邓,則返回列表長度與最短的對象相同,利用 * 號操作符伴鳖,可以將元組解壓為列表节值。
b)語法
zip 語法:zip([iterable, ...])
c)參數(shù)
iterabl -- 一個或多個迭代器。
d)返回值
返回一個對象黎侈。
e)實例
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
zipped = zip(a, b) # 返回一個對象
print("zipped:",zipped)
print("list(zipped):",list(zipped)) # list() 轉(zhuǎn)換為列表
print("list(zip(a, c)):",list(zip(a, c))) # 元素個數(shù)與最短的列表一致
a1, a2 = zip(*zip(a, b)) # 與 zip 相反察署,zip(*) 可理解為解壓,返回二維矩陣式
print("list(a1):",list(a1))
print("list(a2):",list(a2))
運行結(jié)果:
zipped: <zip object at 0x0000020F7E39BA00>
list(zipped): [(1, 4), (2, 5), (3, 6)]
list(zip(a, c)): [(1, 4), (2, 5), (3, 6)]
list(a1): [1, 2, 3]
list(a2): [4, 5, 6]
69峻汉、__import__()
a)描述
原文:
__import__(name, globals=None, locals=None, fromlist=(), level=0)
-> module
Import a module. Because this function is meant for use by the Python interpreter and not for general use, it is better to use importlib.import_module() to programmatically import a module.
The globals argument is only used to determine the context; they are not modified. The locals argument is unused. The fromlist should be a list of names to emulate from name import ...
, or an empty list to emulate import name
.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when fromlist is not empty. The level argument is used to determine whether to perform absolute or relative imports: 0 is absolute, while a positive number is the number of parent directories to search relative to the current module.
中文:
__import__(name, globals=None, locals=None, fromlist=(), level=0)
-> module
導(dǎo)入一個模塊贴汪。因為這個函數(shù)是供Python解釋器使用的,而不是通用的休吠,所以最好使用importlib.import_module()以編程方式導(dǎo)入模塊扳埂。
全局變量僅用于確定上下文;它們沒有被修改。當(dāng)?shù)厝说臓幷撌菦]有用的瘤礁。fromlist應(yīng)該是一個要模擬from name import…
的名稱列表阳懂。或一個空列表來模擬import name
。
當(dāng)從包中導(dǎo)入模塊時岩调,請注意以下幾點:__import__('A.B', ...)
,當(dāng)fromlist為空時返回包A巷燥,當(dāng)fromlist不為空時返回子模塊B。level參數(shù)用于確定是執(zhí)行絕對導(dǎo)入還是相對導(dǎo)入:0是絕對導(dǎo)入号枕,而正數(shù)是相對于當(dāng)前模塊要搜索的父目錄的數(shù)量缰揪。
詮釋:
__import__() 函數(shù)用于動態(tài)加載類和函數(shù) 。
如果一個模塊經(jīng)常變化就可以使用 __import__() 來動態(tài)載入葱淳。
b)語法
__import__ 語法:__import__(name[, globals[, locals[, fromlist[, level]]]])
c)參數(shù)
name:模塊名
d)返回值
返回元組列表钝腺。
e)實例
a.py 文件代碼:
import os
print ('在 a.py 文件中 %s' % id(os))
test.py 文件代碼:
import sys
__import__('a') # 導(dǎo)入 a.py 模塊
運行結(jié)果:
執(zhí)行test.py文件
在 a.py 文件中 2655185398576