Python中文件类型的类字段

Python中文件类型的类字段,python,file,class,Python,File,Class,嗨,我正在尝试为我的班级制作一个日志文件,任何东西都会被写入其中 这是我的班级的样子 class MyClass: f = open('Log.txt','a') def __init__(self): self.f = open('Log.txt', 'a') self.f.write("My Program Started at "+str(datetime.datetime.now())+"\n") def __del

嗨,我正在尝试为我的班级制作一个日志文件,任何东西都会被写入其中

这是我的班级的样子

class MyClass:
    f = open('Log.txt','a')
    def __init__(self):
            self.f = open('Log.txt', 'a')
            self.f.write("My Program Started at "+str(datetime.datetime.now())+"\n")
    def __del__(self):
            self.f.write("closing the log file and terminating...")
            self.f.close()
我的代码可以工作,但正如您在上面看到的,我有两个f=open('Log.txt','a')

有什么办法可以避免吗?
我试图删除其中一个,但它会对我大喊大叫。。。有更好的方法吗?

像这样的方法怎么样:

class Test:
  def __init__(self): #open the file
    self.f=open("log.txt", "w") #or "a"
  def mywrite(self, mytext): #write the text you want
    self.f.write("%s\n" % mytext)
  def myclose(self): #close the file when necessary (you don't need to delete the object)
    self.f.close()

myFile=Test()
myFile.mywrite("abcd")
myFile.myclose()

你应该只有一个

first f=…
在导入时将文件处理程序创建为类属性,因此在您第一次实例化MyClass时,您将打开该处理程序,但是:

MyClass() # and __del__ is called here
MyClass() # f is closed
ValueError: I/O operation on closed file

如果在
\uuuu init\uuuu
方法中执行此操作,则会将处理程序创建为实例属性,并在每次实例化MyClass()时打开该文件,这可能就是您想要的,除非你想在不实例化的情况下使用这个类。

为什么你的类有两个
\uuu init\uu
s?
它会对我大喊大叫
是描述编程问题的模糊方式。准确点。拜托。哦,对不起,我本来应该是这样的。你删除了哪一个?我们需要错误消息