python中用with關鍵字來實現上下文管理器

2021-09-19 09:37:10 字數 1328 閱讀 5352

with open(r'somefilename') as somefile:

for line in somefile:

print line

with 語句的語法

with [as ]:

class pypixcontextmanagerdemo:

def __enter__(self):

print 'entering the block'

def __exit__(self, *unused):

print 'exiting the block'

with pypixcontextmanagerdemo():

print 'in the block'

以mysqldb為例,通常是呼叫mysqldb.connect方法建立的connection的例項的.而在mysqldb中connect方法是這樣實現的.

def connect(*args, **kwargs):

"""factory function for connections.connection."""

from mysqldb.connections import connection

return connection(*args, **kwargs)

而在connection類中實現了__enter__(self),和__exit__(self, *unused)方法

class connection(_mysql.connection):

.....................

def __enter__(self):

if self.get_autocommit():

self.query("begin")

return self.cursor()

def __exit__(self, exc, value, tb):

if exc:

self.rollback()

else:

self.commit()

注意__enter__方法直接返回了cursor物件,因此as後跟的就是乙個cursor物件

with mysqldb.connect(kwargs=mysqldb_kwargs) as ins_cursor:

ins_cursor.execute('select * from user')

new關鍵字 this關鍵字 base關鍵字

使用new,所做的三件事 1.類是引用物件,引用物件是在堆中開闢空間 在堆中開闢空間 2.在開闢的堆空間中建立物件 3.呼叫物件的構建函式 4.隱藏父類成員 子類的成員可以與隱藏從父類繼承的成員,類似於重寫。public new void sayhello this關鍵字的使用 1.代表當前類的物件...

python保留關鍵字和常用關鍵字

python保留關鍵字和常用關鍵字如下 上圖是python3中的關鍵字,python2.7中的關鍵字部分會有區別,具體在自己列印輸出檢視 import keyword print join keyword.kwlist lambda 用於匿名函式中 assert 斷言語句,常用與除錯 raise 用...

this關鍵字 static關鍵字

1.當成員變數和區域性變數重名,可以用關鍵字this來區分 this 代表物件,代表那個物件呢?當前物件 this就是所在函式所屬物件的引用 簡單說 那個物件呼叫了this所在的函式,this就代表哪個物件 this也可以用於在建構函式中呼叫其他建構函式 注意 只能定義在建構函式的第一行,因為初始化...