在类内打开文件

2024-10-01 15:36:50 发布

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

我有个问题。 我需要做的类,这在init打开文件和其他函数只是附加到这个打开的文件文本。我该怎么做? 需要做这样的事情,但这不起作用,所以帮帮我。在

文件1.py

from logsystem import LogginSystem as logsys

file_location='/tmp/test'
file = logsys(file_location)
file.write('some message')

文件2.py

^{pr2}$

谢谢


Tags: 文件函数frompy文本importinitas
1条回答
网友
1楼 · 发布于 2024-10-01 15:36:50

就像前面提到的zwer一样,您可以使用__del__()方法来实现这种行为。在

__del__是与析构函数等价的Python,当对象被垃圾回收时调用。虽然对象实际上会被垃圾回收(这取决于实现),但不保证!在

另一种更安全的方法是使用__enter__和{}方法,它们可以通过以下方式实现:

class LogginSystem(object):

def __enter__(self, file_location):
    self.log_file = open(file_location, 'a+')
    return self

def write(self, message):
    self.log_file.write(message)

def __exit__(self):
    self.log_file.close()

这允许您使用with-语句进行自动清理:

^{pr2}$

您可以阅读有关这些方法的更多信息,以及with-语句here

相关问题 更多 >

    热门问题