首页 > 解决方案 > 我需要明确删除这个对象吗?

问题描述

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

解决方案


在这种情况下,我不会担心它,因为当引用计数变为零时,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 跟踪对象引用计数并知道何时不再需要它们。所以让它为你处理这些事情。


推荐阅读