自定义文件处理程序类

时间:2016-05-27 20:38:45

标签: python class inheritance

我正在开展一个项目,在这个项目中我发现我一再写下这样的内容:

with myfileclass(filename) as output
    # ...

我想写一下:

class Writemyfile(file):

    def _init_(self, filename):
        f = open(filename, 'wb')
        f.write('from _init_ method')
        return f

    def _exit_(self, type, value, traceback):
        self.f.write('from exit method')

        file._exit_(self,type,value,traceback)

with Writeomyfile("test.txt") as output:
    output.write("hello there")

我以为我可以从:

开始
canvas

这显然不起作用,进一步的试验和错误似乎效率非常低。

0 个答案:

没有答案
相关问题