HISIOISIH 发表于 2018-9-8 00:32:04

41课 课后0

这个是41课 写一个 FileObject 类,给文件对象进行包装,从而确认在删除对象时文件能自动关闭

class FileObject:
    def __init__(self,filename='sample.txt'):
      self.new_file=open(filename,'r+')

    def __del__(self):
      self.new_file.close()
      del self.new_file

最后一句 del self.new_file为什么要把self.new_file删了

claws0n 发表于 2018-9-8 00:45:59

__new__() 是构造器,要此函数才能将类实例化为对象。在没有写的情况下,编译器自己会加。
__del__() 是析构器,把对象给删除。

一开始 self.new_file = open() 打开一个文件。最后 self.new_file.close() 文件已经关闭了,不需要用了,所以删除。
页: [1]
查看完整版本: 41课 课后0