【文章內(nèi)容簡介】
__enter__()方法被調(diào)用,這個(gè)方法的返回值將被賦值給as后面的變量。當(dāng)with后面的代碼塊全部被執(zhí)行完之后,將調(diào)用前面返回對(duì)象的__exit__()方法。 This can be demonstrated with the following example: 下面例子可以具體說明with如何工作:12345678910111213141516171819!/usr/bin/env python class Sample:def __enter__(self):print In __enter__()return Foodef __exit__(self, type, value, trace):print In __exit__()def get_sample():return Sample()with get_sample() as sample:print sample:, sampleWhen executed, this will result in: 運(yùn)行代碼,輸出如下1234$ ./In __enter__()sample: FooIn __exit__()As you can see, The __enter__() function is executed The value returned by it in this case Foo is assigned to sample The body of the block is executed, thereby printing the value of sample ie. Foo The __exit__() function is called. What makes with really powerful is the fact that it can handle exceptions. You would have noticed that the __exit__() function for Sample takes three arguments val, type and trace. These are useful in exception handling. Let’s see how this works by modifying the above example. 正如你看到的, 1. __enter__()方法被執(zhí)行 2. __enter__()方法返回的值 這個(gè)例子中是Foo,賦值給變量39。sample39。 3. 執(zhí)行代碼塊,打印變量sample的值為 Foo 4. __exit__()方法被調(diào)用 with真正強(qiáng)大之處是它可以處理異常??赡苣阋呀?jīng)注意到Sample類的__exit__方法有三個(gè)參數(shù) val, type 和 trace。 這些參數(shù)在異常處理中相當(dāng)有用。我們來改一下代碼,看看具體如何工作的。12345678910111213141516171819!/usr/bin/env python class Sample:def __enter__(self):return selfdef __exit__(self, type, value, trace):print type:, typeprint value:, valueprint trace:, tracedef do_something(self):bar = 1/0return bar + 10with Sample() as sample:()Notice how in this example, instead of get_sample(), with takes Sample(). It does not matter, as long as the statement that follows with evaluates to an object that has an __enter__() and __exit__() functions. In this case, Sample()’s __enter__() returns the newly created instance of Sample and that is what gets passed to sample. 這個(gè)例子中,with后面的get_sample()變成了Sample()。這沒有任何關(guān)系,只要緊跟with后面的語句所返回的對(duì)象有__enter__()和__exit__()方法即可。此例中,Sample()的__enter__()方法返回新創(chuàng)建的Sample對(duì)象,并賦值給變量sample。 When executed: 代碼執(zhí)行后:12345678910$ ./type: type 39。39。value: integer division or modulo by zerotrace: traceback object at 0x1004a8128Traceback (most recent call last):File ./, line 19, in module()File ./, line 15, in do_somethingbar = 1/0ZeroDivisionError: integer division or modulo by zeroEssentially, if there are exceptions being thrown from anywhere inside the block, the __exit__() function for the object is called. As you can see, the type, value and the stack trace associated with the exception thrown is passed to this function. In this case, you can see that there was a ZeroDivisionError exception being thrown. People implementing libraries can write code that clean up resources, close files etc. in their __exit__() functions. 實(shí)際上,在with后面的代碼塊拋出任何異常時(shí),__exit__()方法被執(zhí)行。正如例子所示,異常拋出時(shí),與之關(guān)聯(lián)的type,value和stack trace傳給__exit__()方法,因此拋出的ZeroDivisionError異常被打印出來了。開發(fā)庫時(shí),清理資源,關(guān)閉文件等等操作,都可以放在__exit__方法當(dāng)中。 Thus, Python’s with is a nifty construct that makes code a little less verbose and makes cleaning up during exceptions a bit easier. 因此,Python的with語句是提供一個(gè)有效的機(jī)制,讓代碼更簡練,同時(shí)在異常產(chǎn)生時(shí),清理工作更簡單。 I have put the code examples given here on Github. 示例代碼可以在Github上面找到。 生成器 yield:遍歷可以取生成器的值。可以暫時(shí)保存執(zhí)行位置。lambda表達(dá)式:(匿名函數(shù) 只能調(diào)用一次)lambda 參數(shù):表達(dá)式(即返回值)map()函數(shù)與lambda函數(shù)混用Map(函數(shù), 序列) 序列中所有值執(zhí)行函數(shù)Filter(函數(shù), 序列)Reduce(函數(shù),序列)三目運(yùn)算符:Result = 條件為真的值 if 條件 else 條件為假的值內(nèi)置函數(shù):Python:內(nèi)置函數(shù)Python所有的內(nèi)置函數(shù)Builtin Functionsabs()divmod()input()open()staticmethod()all()enumerate()int()ord()str()any()eval()isinstance()pow()sum()basestring()execfile()issubclass()print()super()bin()file()iter()property()tuple()bool()filter()len()range()type()bytearray()float()list()raw_input()unichr()callable()format()locals()reduce()unicode()chr()frozenset()long()reload()vars()classmethod()getattr()map()repr()xrange()cmp()globals()max()reversed()zip()pile()hasattr()memoryview()round()__import__()plex()hash()min()set()apply()delattr()help()next()setattr()buffer()dict()hex()object()slice()coerce()dir()id()oct()sorted()intern()常用的內(nèi)置函數(shù)內(nèi)置方法說明__init__(self,...)初始化對(duì)象,在創(chuàng)建新對(duì)象時(shí)調(diào)用__del__(self)釋放對(duì)象,在對(duì)象被刪除之前調(diào)用__new__(cls,*args,**kwd)實(shí)例的生成操作__str__(self)在使用print語句時(shí)被調(diào)用__getitem__(self,key)獲取序列的索引key對(duì)應(yīng)的值,等價(jià)于seq[key]__len__(self)在調(diào)用內(nèi)聯(lián)函數(shù)len()時(shí)被調(diào)用__cmp__(stc,dst)比較兩個(gè)對(duì)象src和dst__getattr__(s,name)獲取屬性的值__setattr__(s,name,value)設(shè)置屬性的值__delattr__(s,name)刪除name屬性__getattribute__()__getattribute__()功能與__getattr__()類似__gt__(self,other)判斷self對(duì)象是否大于other對(duì)象__lt__(slef,other)判斷self對(duì)象是否小于other對(duì)象__ge__(slef,other)判斷self對(duì)象是否大于或者等于other對(duì)象__le__(slef,other)判斷self對(duì)象是否小于或者等于other對(duì)象__eq__(slef,other)判斷self對(duì)象是否等于other對(duì)象__call__(self,*args)把實(shí)例對(duì)象作為函數(shù)調(diào)用__init__()__init__方法在類的一個(gè)對(duì)象被建立時(shí),馬上運(yùn)行。這個(gè)方法可以用來對(duì)你的對(duì)象做一些你希望的初始化。注意,這個(gè)名稱的開始和結(jié)尾都是雙下劃線。代碼例子:!/usr/bin/python Filename: Person: def __init__(self, name): = name def sayHi(self): print 39。Hello, my name is39。, p = Person(39。Swaroop39。)()輸出:Hello, my name is Swaroop說明:__init__方法定義為取一個(gè)參數(shù)name(以及普通的參數(shù)self)。在這個(gè)__init__里,我們只是創(chuàng)建一個(gè)新的域,也稱為name。注意它們是兩個(gè)不同的變量,盡管它們有相同的名字。點(diǎn)號(hào)使我們能夠區(qū)分它們。最重要的是,我們沒有專門調(diào)用__init__方法,只是在創(chuàng)建一個(gè)類的新實(shí)例的時(shí)候,把參數(shù)包括在圓括號(hào)內(nèi)跟在類名后面,從而傳遞給__init__方法。這是這種方法的重要之處。現(xiàn)在。這在sayHi方法中得到了驗(yàn)證。__new__()__new__()在__init__()之前被調(diào)用,單例模式設(shè)計(jì)的類只能實(shí)例化一個(gè)對(duì)象.!/usr/bin/python * coding: UTF8 *class Singleton(object): __instance = None 定義實(shí)例 def __init__(self): pass def __new__(cls, *args, **kwd): 在__init__之前調(diào)用 if is None: 生成唯一實(shí)例 = (cls, *args, **kwd)