2013-05-02 20 views
0

塊在Ruby中,我可以說:類在Python

def get_connection 
    db = connect_to_db() 
    yield 
    db.close() 
end 

然後調用它

get_connection do 
    # action1..... 
    # action2..... 
    # action3..... 
end 

在Python,我不得不說

def get_connection(code_block): 
    db = connect_to_db() 
    code_block() 
    db.close() 

get_connection(method1) 

def method1(): 
    # action1..... 
    # action2..... 
    # action3..... 

這並不方便,因爲我必須創建一個額外的method1。請注意,method1可能很大。有沒有什麼辦法模仿Python中的Ruby匿名塊?

回答

4

是的。 '與' 語句使用:

使用類

class get_connection(object): 
    def __enter__(self): 
     self.connect_to_db() 
    def __exit__(self, *args, **kwargs): 
     self.close() 
    def some_db_method(self,...): 
     ... 

而且使用這樣的:

with get_connection() as db: 
    db.some_db_method(...) 

這將執行以下操作:

self.connect_to_db() 
db.some_db_method(...) 
self.close() 

這裏看看: http://docs.python.org/release/2.5/whatsnew/pep-343.html。您可以使用__exit__with語句內處理異常所採取的參數等

使用功能

from contextlib import contextmanager 

@contextmanager 
def db_connection(): 
    db = connect_to_db() 
    yield db 
    db.close() 

,並使用此:

with db_connection() as db: 
    db.some_db_method() 

(也許這是更接近你的紅寶石同樣,在這裏看到更多的細節:http://preshing.com/20110920/the-python-with-statement-by-example

希望這可以幫助

+0

我可以擺脫創建班級嗎? – 2013-05-02 05:11:28

+0

@AlanDert見我編輯 – 2013-05-02 05:17:21

+0

爲什麼不使用本地方法? – 2013-05-02 05:24:27