在modu中实例化一个类

2024-06-16 09:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我来自ruby背景,我注意到了python的一些不同之处。。。在ruby中,当我需要创建一个helper时,我通常选择一个模块,如下所示:

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

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

在pytho中,我执行如下操作:

^{pr2}$

我唯一担心的是每次调用query()函数时,它都会一遍又一遍地实例化DBClient()。。。但是根据阅读和测试,当我导入一个模块时,由于python中的一些缓存机制,这似乎不会发生。。。在

问题是,在python中,上面的内容是否是不好的实践,如果是,为什么以及如何改进?也许懒得去评价它?或者如果你们认为这没关系。。。在


Tags: 模块helperclientnewdbdefqueryselect
2条回答

简而言之,您想向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")

归于Igor Sobreira。在

不需要。query函数不会在每次调用时都被重新实例化。这是因为您已经在query函数的之外创建了一个DBClient的实例。这意味着您当前的代码是正常的。在

如果您的目的是在每次调用query时创建一个DBClient的新实例,那么您只需将声明移动到query函数中,如下所示:

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

相关问题 更多 >