2015-11-04 95 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