0

I'm trying to create a instance of a class to test that the module I created is working properly.

Here is the module (fileWriter.py), the error appears to be in the init method:

class File(object):
'''process the data from a file'''

#fields
#fileName = name of file
#textData = data read from/written to 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 to file'''
    try:
        fileObj = open(self.fileName, 'a')
        fileObj.write(self.textData)
        fileObj.close()
    except Exception as e:
        print('You have the following error: ' + str(e))
    return('Data successfully saved to 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 the class, I wrote the 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 a module by itself!')

When I run the test file, I get the 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 with self.textData = textData. Can anybody help?

1 Answer 1

2

I'm not sure if you formatted your code after pasting, but there are a few typos:

def __init__(self, file_name = 'saved_data.txt', text_data = ''):
    #Attributes
    self.__file_name = file_name
    self.__text_data = text_data

and

@property #getter
def text_data(self):
    return self.__text_data

Later in test, you're also trying to set the text_data property without a setter in your example. You can add to your class:

@textData.setter
def text_data(self, value):
    self.__text_data = value

The more pythonic way to do some of the file io stuff is with a context.

def save_data(self):
    '''appends data to file'''

    with open(self.file_name, 'a') as f:
        f.write(self.text_data)
    return('Data successfully saved to file.')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.