【问题标题】:Accessing class file from multiple methods in Python从 Python 中的多个方法访问类文件
【发布时间】:2015-07-01 09:09:58
【问题描述】:

我的问题主要与您如何在 Python 的类中使用 with 关键字有关。

如果你有一个包含文件对象的类,你如何使用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 退出并可能关闭文件?

【问题讨论】:

  • 永远不要给自己的属性或方法两边加上双下划线。这些名称是为 Python 自己的属性设计的,您可以覆盖这些属性,但不能定义您自己的。

标签: python file with-statement


【解决方案1】:

是的,你是对的,with 会在其作用域结束时自动关闭文件,所以如果你在__init__() 函数中使用with 语句,write_something 函数将不起作用。

也许您可以在程序的主要部分使用with 语句,而不是在__init__() 函数中打开文件,您可以将文件对象作为参数传递给__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

虽然这会使事情复杂化很多,但最好不要使用with 语句,而是确保在需要结束时关闭文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2021-11-16
    • 2018-10-21
    • 2012-11-12
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多