我有一个菜鸟问题。我需要做这个类,它在 init 打开文件和其他函数中只是附加到这个打开的文件文本。我怎么能做到这一点?需要做这样的事情,但这不起作用,所以帮助。
文件1.py
from logsystem import LogginSystem as logsys
file_location='/tmp/test'
file = logsys(file_location)
file.write('some message')
Run Code Online (Sandbox Code Playgroud)
文件2.py
class LogginSystem(object):
def __init__(self, file_location):
self.log_file = open(file_location, 'a+')
def write(self, message):
self.log_file.write(message)
Run Code Online (Sandbox Code Playgroud)
谢谢
小智 5
就像zwer已经提到的那样,您可以使用该__del__()方法来实现这种行为。
__del__是 Python 等价的析构函数,在对象被垃圾回收时调用。这是不保证的,虽然该物体实际上是垃圾收集(这是实现有关)!
另一种更安全的方法是使用__enter__和__exit__方法,可以通过以下方式实现:
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()
Run Code Online (Sandbox Code Playgroud)
这允许您使用with-statement 进行自动清理:
from logsystem import LogginSystem as logsys
file_location='/tmp/test'
with logsys(file_location) as file:
file.write('some message')
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关这些方法的更多信息以及with-statement
| 归档时间: |
|
| 查看次数: |
5007 次 |
| 最近记录: |