Python附加到在类中打开的文件

时间:2015-01-31 21:20:36

标签: python class append

这是我的python代码。我正在尝试创建一个执行文件的类 操纵。我使用了与此URL类似的结构,但我无法附加到文件中。

add_to_file.py -----------

import os
import sys

class add_to_file(object):
    def __init__(self, filename):
        self.data_file = open(filename,'a')
    def __enter__(self):  # __enter__ and __exit__ are there to support
        return self       # `with self as blah` syntax
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.data_file.close()
    def __iter__(self):
        return self
    def __append__(s):
        self.data_file.write(s)
    __append__("PQR")

add_to_file("Junk")

结果-------------------

Traceback (most recent call last):
  File "add_to_file.py", line 4, in <module>
    class add_to_file(object):
  File "add_to_file.py", line 15, in add_to_file
    __append__("PQR")
  File "add_to_file.py", line 14, in __append__
    self.data_file.write(s)
NameError: global name 'self' is not defined

2 个答案:

答案 0 :(得分:2)

def __append__(s):更改为def __append__(self, s):

答案 1 :(得分:0)

目前还不清楚你究竟想要完成什么 - 它看起来有点像上下文管理器类。我将__append__()重命名为append(),因为以双重下划线开头和结尾的方法只能由语言定义,我根据{add_to_file将您的类重命名为AddToFile {3}}

import os
import sys

class AddToFile(object):
    def __init__(self, filename):
        self.data_file = open(filename,'a')
    def __enter__(self):  # __enter__ and __exit__ are there to support
        return self       # `with self as blah` syntax
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.data_file.close()
    def __iter__(self):
        return self
    def append(self, s):
        self.data_file.write(s)


with AddToFile("Junk") as atf:
    atf.append("PQR")

with open("Junk") as file:
    print(file.read())  # --> PQR