2015-11-04 136 views
0

我來自一個紅寶石背景,我注意到一些區別python ...在紅寶石,當我需要創建一個幫手我通常去模塊,如下所示:在模塊中實例化一個類

module QueryHelper 
    def db_client 
    @db ||= DBClient.new 
    end 

    def query 
    db_client.select('whateverquery') 
    end 
end 

在Python中壽,我像做了以下內容:

db_client = DBClient() 

def query(): 
    return db_client.select('whateverquery') 

我與上面唯一擔心的是,每次我打電話查詢()時間的函數,它會嘗試實例化與dbclient()一遍又一遍...但基於閱讀和測試,這似乎並不是由於python中的一些緩存機制,當我即時通訊端口模塊...

問題是,如果上面的python是不好的做法,如果是的話,爲什麼以及如何改進?也許懶惰的評估呢?或者,如果你們認爲它沒問題...

+0

'db_client'是'DBClient'的一個實例,所以任何使用'db_client.'的調用都使用同一個實例(只要這個名字沒有指向其他任何地方)。但是,如果你想使用'DBClient()。select('whatever')',那麼在每次調用query()時都會創建一個新實例(並快速垃圾回收)。 – Jkdc

回答

2

不可以。每次調用它時,query函數都不會被重新實例化。這是因爲您已經在query函數的之外創建了DBClient的實例。這意味着你現在的代碼沒問題。

如果你的目的是創造DBClient一個新實例每次query被調用,那麼您應該只是移動宣佈進入query功能,像這樣:

def query(): 
    db_client = DBClient() 
    return db_client.select(...) 
-1

總之你想添加一個DBClient對象的方法?爲什麼不動態添加它?

# defining the method to add 
def query(self, command): 
    return self.select(command) 

# Actually adding it to the DBClient class 
DBClient.query = query 

# Instances now come with the newly added method 
db_client = DBClient() 

# Using the method 
return_command_1 = db_client.query("my_command_1") 
return_command_2 = db_client.query("my_command_2") 

Credits to Igor Sobreira

+0

其實我正在尋找使用DBClient中的方法...只是想知道我使用我的模塊的方式並在模塊中實例化我的類是可以接受的......顯然它是... – Bodao

+0

哦,那麼你只需要這樣做: 'db_client = DBClient() return_command_1 = db_client.query(「my_command_1」) return_command_2 = db_client.query(「my_command_2」)' – joris255