Python类变量资源化时如何自动清除类变量

2024-05-16 07:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python类中处理变量时遇到了一个问题。我有一个代码如下。在

class TempClass:
    resource = xlwings.Book() # xlwings is a library manipulating Excel file.

    #...

在这里,要清除“资源”,我需要执行

^{pr2}$

清除类(而不是对象)时是否有内置函数被调用,以便我可以在该函数中编写上述代码?或者有没有办法清除“资源”?在

我的Python版本是3.6


Tags: 对象函数代码islibrary资源xlwingsexcel
1条回答
网友
1楼 · 发布于 2024-05-16 07:30:02

不要使用类变量。只要类存在,类变量就一直是活动的,可能只要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显示每个方法的调用位置:

^{pr2}$

哪个打印:

before the context
init
inside the context
close
after the context

相关问题 更多 >