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(),當然也可以不實例化調(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'值(默認值為0)和一個可迭代的數(shù)字的總和。
當iterable為空時,返回初始值。
此函數(shù)專門用于數(shù)值類型,可以拒絕非數(shù)值類型。
詮釋:
sum() 方法對系列進行求和計算。
b)語法
sum() 方法的語法:sum(iterable[, start])
c)參數(shù)
iterable:可迭代對象,如:列表、元組、集合。
start:指定相加的參數(shù),如果沒有設(shè)置這個值,默認為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)、重復調(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:
在學習 Python 類的時候,總會碰見書上的類中有 init() 這樣一個函數(shù),很多同學百思不得其解,其實它就是 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)造方法之后,我們來點進階的問題,那就是構(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() 不會認為子類是一種父類類型,不考慮繼承關(guān)系。
isinstance() 會認為子類是一種父類類型,考慮繼承關(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ù),就打印當前調(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
導入一個模塊。因為這個函數(shù)是供Python解釋器使用的,而不是通用的,所以最好使用importlib.import_module()以編程方式導入模塊。
全局變量僅用于確定上下文;它們沒有被修改。當?shù)厝说臓幷撌菦]有用的。fromlist應(yīng)該是一個要模擬from name import…的名稱列表?;蛞粋€空列表來模擬import name。
當從包中導入模塊時,請注意以下幾點:__import__('A.B', ...),當fromlist為空時返回包A,當fromlist不為空時返回子模塊B。level參數(shù)用于確定是執(zhí)行絕對導入還是相對導入:0是絕對導入,而正數(shù)是相對于當前模塊要搜索的父目錄的數(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') # 導入 a.py 模塊
運行結(jié)果:
執(zhí)行test.py文件
在 a.py 文件中 2655185398576