python - 我需要明确删除这个对象吗?
问题描述
class Tokenizer()
def __init__(self):
self.name = 'MyTokenizer'
self.tokenizer = Language.create_tokenizer(nlp)
def __call__(self, text):
if text:
with CoreClient(timeout=60000) as client:
doc = client.annotate(text, output_format='json')
else:
doc = Document("")
...
我遇到的问题是“CoreClient”的创建,它创建了一个对服务器的 http 请求。“with ... as client”引入的当前代码可以确保在完成后“client.annotate”超出范围时销毁客户端。但是,问题在于,必须为处理“文本”的每个请求创建对象“客户端”。为了避免这种情况,我最好在 init 方法中创建对象:
self.client = CoreClient(timeout=60000)
但是之后:
1) How to destroy the 'client' after all requests have been completed? OR
2) Is the current way of creating a Coreclient OK for each request? The creation of the object is heavy, which needs a lot of initialization.
编辑:
def __enter__(self):
self.start()
return self
def start(self):
if self.start_cmd:
if self.be_quiet:
# Issue #26: subprocess.DEVNULL isn't supported in python 2.7.
stderr = open(os.devnull, 'w')
else:
stderr = self.stderr
print(f"Starting server with command: {' '.join(self.start_cmd)}")
self.server = subprocess.Popen(self.start_cmd,
stderr=stderr,
stdout=stderr)
为了更清楚,我添加了方法enter的实现。它似乎只是返回对象'self'。
解决方案
在这种情况下,我不会担心它,因为当引用计数变为零时,Python 会处理它。此外,del
实际上并不删除和反对。可能会,但可能不会。del
将减少对对象的引用计数。
以此为例:
In [1]: class Test:
...: def __del__(self):
...: print('deleted')
...:
In [2]: t = Test()
In [3]: del t
deleted
In [4]: t = Test()
In [5]: t1 = t
In [6]: del t # Nothing gets printed here because t1 still exists
In [7]: del t1 # reference count goes to 0 and now gets printed
deleted
这就是为什么我认为你应该让 Python 处理你的对象的销毁。Python 跟踪对象引用计数并知道何时不再需要它们。所以让它为你处理这些事情。
推荐阅读
- python - ODOO 14,如何通过模板中的rest api渲染另一个模板?
- matlab - MATLAB,fitcknn 使用梅尔频率倒谱系数 (MFCC)
- ruby-on-rails - OmniAuth:secret 或 digest 到底是什么意思?如何获得?
- r - R 计算条件 = 0 的连续天数
- python - 如何在 Python 3.8 中为基类使用带引号的类型注释?
- node.js - 未捕获(承诺)错误:群视频聊天项目中的 InvalidStateError
- node.js - 从插入流“返回”用于 pg-promise
- pip - 为什么我无法通过 PIP 安装 python 模块
- css - CSS 嵌套类定义
- java - 如何从firebase数据库实时数据库中获取前一个孩子的价值?