Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 实例化模块中的类_Python - Fatal编程技术网

Python 实例化模块中的类

Python 实例化模块中的类,python,Python,我来自ruby背景,我注意到与python的一些区别。。。在ruby中,当我需要创建助手时,我通常会选择一个模块,如下所示: module QueryHelper def db_client @db ||= DBClient.new end def query db_client.select('whateverquery') end end 在python tho中,我执行以下操作: db_client = DBClient() def query():

我来自ruby背景,我注意到与python的一些区别。。。在ruby中,当我需要创建助手时,我通常会选择一个模块,如下所示:

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

  def query
    db_client.select('whateverquery')
  end
end
在python tho中,我执行以下操作:

db_client = DBClient()

def query():
    return db_client.select('whateverquery')
我唯一担心的是,每次调用query()函数时,它都会一次又一次地实例化DBClient()。。。但基于阅读和测试,这似乎并没有发生,因为在我导入模块时python中有一些缓存机制


问题是,如果python中的上述做法不好,那么为什么以及如何改进?也许是懒惰?或者,如果你们认为这是好的,因为是

否。
查询
函数不会在每次调用时重新实例化。这是因为您已经在
query
函数之外创建了
DBClient
的实例。这意味着您当前的代码可以正常运行

如果您打算在每次调用
query
时创建
DBClient
的新实例,那么您应该将声明移动到
query
函数中,如下所示:

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

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

归功于。

db\u client
DBClient
的一个实例,因此任何使用
db\u client.
的调用都使用相同的实例(只要该名称不指向其他任何地方)。然而,相比之下,如果要使用
DBClient().select('whatever')
,那么每次调用
query()
,都会创建一个新实例(并快速进行垃圾收集)。实际上,我希望在DBClient中使用一个方法。。。只是想知道我在模块中使用模块和实例化类的方式是否可以接受。。。显然是…哦,那么你只需要这样做:
db\u client=DBClient()return\u command\u 1=db\u client.query(“my\u command\u 1”)return\u command\u 2=db\u client.query(“my\u command\u 2”)