【问题标题】:Python append to file opened inside a classPython追加到类中打开的文件
【发布时间】:2015-03-31 03:41:48
【问题描述】:

这是我的 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

【问题讨论】:

  • def __append__(self, s) 有效吗?

标签: python class append


【解决方案1】:

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

【讨论】:

  • 回溯(最近一次调用最后):文件“add_to_file.py”,第 4 行,在 类 add_to_file(object):文件“add_to_file.py”,第 15 行,在 add_to_file append__("Junk","PQR") 文件“add_to_file.py”,第 14 行,在 __append self.data_file.write(s) AttributeError: 'str' object has no attribute 'data_file'
【解决方案2】:

目前还不清楚您到底想要完成什么——它看起来有点像上下文管理器类。我将__append__() 重命名为append(),因为以双下划线开头和结尾的方法只能由语言定义,并且我根据PEP 8 - Style Guide for Python Code 将您的类从add_to_file 重命名为AddToFile

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

【讨论】:

  • 谢谢,效果很好。仍在尝试弄清楚一些基础知识__beginer_newbie
  • 最重要的错误是在类定义本身中调用append() 方法,并且在其定义中没有初始self 参数。
猜你喜欢
  • 1970-01-01
  • 2021-12-13
  • 2020-01-31
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多