can't set attribute in class instance in Python -
i'm trying create instance of class test module created working properly.
here module (filewriter.py), error appears in init method:
class file(object): '''process data file''' #fields #filename = name of file #textdata = data read from/written file #constructor def __init__(self, filename = 'saved_data.txt', textdata = ''): #attributes self.filename = filename self.textdata = textdata #properties @property #getter def filename(self): return self.__filename @filename.setter #setter def filename(self, value): self.__filename = value @property #getter def textdata(self, value): self.__textdata = value #methods def savedata(self): '''appends data file''' try: fileobj = open(self.filename, 'a') fileobj.write(self.textdata) fileobj.close() except exception e: print('you have following error: ' + str(e)) return('data saved file.') def tostring(self): '''returns text data explicitly''' return self.filename + ':' + self.textdata def __str__(self): '''returns text data implicitly''' return self.tostring()
to test class, wrote following test harness:
import filewriter import filewriter #test harness processorobj = filewriter.file() processorobj.filename = 'test.txt' processorobj.textdata = 'testing, 1, 2, 3...' strmessage = processorobj.savedata() print(strmessage) if __name__ == '__main__': raise exception('don\'t run module itself!')
when run test file, error:
file "testfilewriter.py", line 4, in processorobj = filewriter.file() file "/users/haruka/documents/python_class/employees/filewriter.py", line 19, in init self.textdata = textdata attributeerror: can't set attribute
i can't figure out what's wrong self.textdata = textdata. can help?
i'm not sure if formatted code after pasting, there few typos:
def __init__(self, filename = 'saved_data.txt', textdata = ''): #attributes self.__filename = filename self.__textdata = textdata
and
@property #getter def textdata(self): return self.__textdata
later in test, you're trying set textdata property without setter in example. can add class:
@textdata.setter def textdata(self, value): self.__textdata = value
the more pythonic way of file io stuff context.
def savedata(self): '''appends data file''' open(self.filename, 'a') f: f.write(self.textdata) return('data saved file.')
Comments
Post a Comment