我试图在python中自学对象编程。 我希望我的动词只是对象的那个实例,我认为这是通过使用self.verbalname完成的。
现在我收到了包含self.file的每一行的错误 对象没有属性文件
中的例子def open(self):
# open file
self.file = open(self.filename,"r",1);
我收到错误消息
CODE
class spreedsheet(object):
def __init__(self, name):
self.filename = name
def getFileName(self):
print(self.filename)
def open(self):
# open file
THIS LINE GIVES ME A ERROR SAYING OBJECT HAS NO ATTRIBUTE FILE
self.file = open(self.filename,"r",1);
def close(self):
# close file
THIS LINE GIVES ME A ERROR SAYING OBJECT HAS NO ATTRIBUTE FILE
self.file.close();
def addString(self,add):
# add a string to a line of the spreed sheet
THIS LINE GIVES ME A ERROR SAYING FILE DOES NOT EXIST
self.file.write(add)
self.write(",")
def addStringRet(self,name):
# add a string to a line of the spreed sheet
THIS LINE GIVES ME A ERROR SAYING FILE DOES NOT EXIST
self.file.write(add)
self.write("\r\n")
# Add a new string and start a new col
myobject = spreedsheet("agraphdata.txt")
myobject.addString("tedt")
myobject.close()
答案 0 :(得分:0)
您还没有在file
类的任何位置定义实例变量spreadsheet
,因此实例方法确实知道它是什么。将其添加到构造函数中:
class spreedsheet(object):
def __init__(self, name):
self.filename = name
self.file = None
def getFileName(self):
print(self.filename)
def open(self):
self.file = open(self.filename,"r",1);
etc