2024-05-16 07:30:02 发布
网友
我在Python类中处理变量时遇到了一个问题。我有一个代码如下。在
class TempClass: resource = xlwings.Book() # xlwings is a library manipulating Excel file. #...
在这里,要清除“资源”,我需要执行
清除类(而不是对象)时是否有内置函数被调用,以便我可以在该函数中编写上述代码?或者有没有办法清除“资源”?在
我的Python版本是3.6
不要使用类变量。只要类存在,类变量就一直是活动的,可能只要python解释器没有关闭。在
通常,对于需要关闭的资源,您可以简单地使用contextmanager(例如^{}):
import contextlib # I don't have xlwings so I create some class that acts like it: class Book(object): def __init__(self): print('init') def close(self): print('close')
实际的“上下文”可以这样创建和使用。在块内部,资源是活动的,并且在块结束后被关闭。我使用prints显示每个方法的调用位置:
print
哪个打印:
before the context init inside the context close after the context
不要使用类变量。只要类存在,类变量就一直是活动的,可能只要python解释器没有关闭。在
通常,对于需要关闭的资源,您可以简单地使用contextmanager(例如^{} ):
实际的“上下文”可以这样创建和使用。在块内部,资源是活动的,并且在块结束后被关闭。我使用
^{pr2}$print
s显示每个方法的调用位置:哪个打印:
相关问题 更多 >
编程相关推荐