0
我試圖創建一個類的實例來測試我創建的模塊是否正常工作。無法在Python中的類實例中設置屬性
這裏是模塊(fileWriter.py),誤差似乎是在INIT方法:
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()
要測試類,我寫了下面的測試工具:
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!')
當我運行測試文件時,出現錯誤:
文件「testFileWriter.py」,第4行,在 processorObj = file Writer.File() 文件 「/Users/Haruka/Documents/python_class/Employees/fileWriter.py」,第19行,在初始化 self.textData =的TextData AttributeError的:不能設置屬性
我無法弄清楚self.textData = textData有什麼問題。任何人都可以幫忙嗎?