Python內(nèi)置函數(shù)(7)

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__()雁芙。

內(nèi)置函數(shù)(原文)
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
內(nèi)置函數(shù)(中文)
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
Python內(nèi)置函數(shù).png

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市赞厕,隨后出現(xiàn)的幾起案子艳狐,更是在濱河造成了極大的恐慌,老刑警劉巖皿桑,帶你破解...
    沈念sama閱讀 211,376評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件毫目,死亡現(xiàn)場離奇詭異,居然都是意外死亡唁毒,警方通過查閱死者的電腦和手機蒜茴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,126評論 2 385
  • 文/潘曉璐 我一進(jìn)店門星爪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來浆西,“玉大人,你說我怎么就攤上這事顽腾〗悖” “怎么了?”我有些...
    開封第一講書人閱讀 156,966評論 0 347
  • 文/不壞的土叔 我叫張陵抄肖,是天一觀的道長久信。 經(jīng)常有香客問我,道長漓摩,這世上最難降的妖魔是什么裙士? 我笑而不...
    開封第一講書人閱讀 56,432評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮管毙,結(jié)果婚禮上腿椎,老公的妹妹穿的比我還像新娘。我一直安慰自己夭咬,他們只是感情好啃炸,可當(dāng)我...
    茶點故事閱讀 65,519評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著卓舵,像睡著了一般南用。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,792評論 1 290
  • 那天裹虫,我揣著相機與錄音肿嘲,去河邊找鬼。 笑死筑公,一個胖子當(dāng)著我的面吹牛睦刃,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播十酣,決...
    沈念sama閱讀 38,933評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼涩拙,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了耸采?” 一聲冷哼從身側(cè)響起兴泥,我...
    開封第一講書人閱讀 37,701評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎虾宇,沒想到半個月后搓彻,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,143評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡嘱朽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,488評論 2 327
  • 正文 我和宋清朗相戀三年旭贬,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片搪泳。...
    茶點故事閱讀 38,626評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡稀轨,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出岸军,到底是詐尸還是另有隱情奋刽,我是刑警寧澤,帶...
    沈念sama閱讀 34,292評論 4 329
  • 正文 年R本政府宣布艰赞,位于F島的核電站佣谐,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏方妖。R本人自食惡果不足惜狭魂,卻給世界環(huán)境...
    茶點故事閱讀 39,896評論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望党觅。 院中可真熱鬧雌澄,春花似錦、人聲如沸仔役。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,742評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽又兵。三九已至任柜,卻和暖如春卒废,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背宙地。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工摔认, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人宅粥。 一個月前我還...
    沈念sama閱讀 46,324評論 2 360
  • 正文 我出身青樓参袱,卻偏偏與公主長得像,于是被迫代替她去往敵國和親秽梅。 傳聞我的和親對象是個殘疾皇子抹蚀,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,494評論 2 348