我的问题主要涉及如何在Python中的类中使用with
关键字。
如果您有一个包含文件对象的Class,那么如何使用with
语句(如果有的话)。
例如,我在这里不使用with
:
class CSVLogger:
def __init__(self, rec_queue, filename):
self.rec_queue = rec_queue
## Filename specifications
self.__file_string__ = filename
f = open(self.__file_string__, 'wb')
self.csv_writer = csv.writer(f, newline='', lineterminator='\n', dialect='excel')
如果我在另一种方法中对文件执行操作,例如:
def write_something(self, msg):
self.csv_writer(msg)
这适合吗?我应该在某处包含with
吗?我只是担心__init__
退出,with
退出并关闭文件?
答案 0 :(得分:1)
是的,你是正确的with
在范围结束时自动关闭文件,所以如果你在with
函数中使用__init__()
语句,write_something函数将无效。
也许你可以在程序的主要部分使用with
语句,而不是在__init__()
函数中打开文件,你可以将文件对象作为参数传递给{{1功能。然后在__init__()
块中的文件中执行您想要执行的所有操作。
示例 -
类看起来像 -
with
主程序可能看起来像 -
class CSVLogger:
def __init__(self, rec_queue, filename, f):
self.rec_queue = rec_queue
## Filename specifications
self.__file_string__ = filename
self.csv_writer = csv.writer(f, newline='', lineterminator='\n', dialect='excel')
def write_something(self, msg):
self.csv_writer(msg)
虽然如果这样做很复杂,但最好不要使用with open('filename','wb') as f:
cinstance = CSVLogger(...,f) #file and other parameters
.... #other logic
cinstance.write_something("some message")
..... #other logic
语句,而是确保在需要结束时关闭文件。