Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—当类变量是资源时,如何自动清除类变量_Python_Resources_Xlwings - Fatal编程技术网

Python—当类变量是资源时,如何自动清除类变量

Python—当类变量是资源时,如何自动清除类变量,python,resources,xlwings,Python,Resources,Xlwings,我在Python中处理类变量时遇到问题。我有如下代码 class TempClass: resource = xlwings.Book() # xlwings is a library manipulating Excel file. #... 在这里,要清除“资源”,我需要执行 resource.close() 清除类(而不是对象)时是否调用了任何内置函数,以便我可以在该函数中编写上述代码?或者有没有办法清除“资源” 我的Python版本是3.6,不要使用类变量。只要类存

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

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

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

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


我的Python版本是3.6,不要使用类变量。只要类存在,或者只要python解释器没有关闭,类变量就处于活动状态

通常,对于需要关闭的资源,您只需使用contextmanager(例如):

实际的“上下文”可以这样创建和使用。在块内部,资源处于活动状态,并且在块结束后关闭。我使用
print
s显示调用每个方法的位置:

print('before the context')
with contextlib.closing(Book()):
    print('inside the context')
print('after the context')
其中打印:

before the context
init
inside the context
close
after the context

当一个类被“清除”时,你是什么意思?我猜你说的是当你覆盖tempclass(的对象)的数据时。您可以在temp类中创建一个方法,该方法首先执行resource.close(),然后将对象设置为任何输入方法,并使用该方法而不是普通的obj=(新事物)。使用类而不是实例有什么原因吗?您可以更轻松地将上下文管理器与实例一起使用。寻找example@OwenCummings所以你的意思是制作一个用户不使用的实例?我认为这是个好主意!嗯……但是如果我使用“contextlib”,我需要在“scope”中使用“Book”编写所有代码。实际上,在我的代码中,在我的程序关闭之前,所有的“TempClass”实例都使用“resource”。就我个人而言,在程序关闭之前,我不会让文件句柄保持打开状态。大多数情况下,您只需要在极少数部分中使用它,这些部分可以很容易地放入上下文管理器中。@younghoonjeng是的,一切都会在
范围内发生。将块放入函数中,并将
Book
作为参数传递。
before the context
init
inside the context
close
after the context