【发布时间】: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) 有效吗?