我正在编写一个类似于连接的对象,它实现了上下文管理器。强烈建议编写以下内容:
with MyConnection() as con:
# do stuff
当然,也可以这样做:
con = MyConnection()
# do stuff
con.close()
但是未能关闭连接会带来一些问题。因此,在__del__()
中关闭连接似乎是一个不错的主意:
def __del__(self):
self.close()
这看起来很不错,但有时会导致错误:
Exception ignored in: [...]
Traceback (most recent call last):
File "...", line xxx, in __del__()
TypeError: 'NoneType' object is not callable
似乎有时在调用__del__()
方法时,关闭方法已经被销毁。
因此,我正在寻找一种好的方法来鼓励Python在销毁时正常关闭连接。如果可能,我想避免在close()
和__del__()
中重复编写代码。
__exit__
。 - jonrsharpeclose
调用__del__
。不要过于保护用户——毕竟他们是程序员,应该足够聪明地使用你提供给他们的 API——只需确保你有良好的文档,其余的就交给他们了。 - Ethan Furman__del__
有点丑陋。我认为你是对的 - 太过关注用户误用代码可能不是一个好主意,特别是当代码变得相当混乱时。 - cel