从 Python 中的多种方法访问 class 文件
Accessing class file from multiple methods in Python
我的问题主要与您如何在 Python 中的 class 中使用 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
退出并可能关闭文件?
是的,你是对的 with
在文件作用域结束时自动关闭文件,所以如果你在 __init__()
函数中使用 with
语句,write_something 函数不行。
也许您可以在程序的主体部分使用 with
语句,而不是在 __init__()
函数中打开文件,您可以将文件对象作为参数传递给 __init__()
函数。然后在 with
块内的文件中执行您想执行的所有操作。
例子-
Class 看起来像 -
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
虽然这会使事情复杂化很多,但您最好不要使用 with
语句,而是确保在需要时关闭文件。
我的问题主要与您如何在 Python 中的 class 中使用 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
退出并可能关闭文件?
是的,你是对的 with
在文件作用域结束时自动关闭文件,所以如果你在 __init__()
函数中使用 with
语句,write_something 函数不行。
也许您可以在程序的主体部分使用 with
语句,而不是在 __init__()
函数中打开文件,您可以将文件对象作为参数传递给 __init__()
函数。然后在 with
块内的文件中执行您想执行的所有操作。
例子-
Class 看起来像 -
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
虽然这会使事情复杂化很多,但您最好不要使用 with
语句,而是确保在需要时关闭文件。