-6

these are her instructions:

  • Write a class called TemperatureFile.
  • The class has one data attribute: __filename
  • Write getter and setter for the data attribute.
  • Write a “calculateAverage” function (signature below) to calculate and
  • return average temperature of all temperatures in the file.
  • def calculateAverage(self):
  • Handle possible exceptions
  • Write a main function:
  • Create a file ('Temperatures.txt’) and then use “write” method to write
  • temperature values on each line.
  • Create an object of the TemperaureFile with the filename
  • (‘Temperatures.txt’) just created
  • Use the object to call calcuateAverage function and print out the
  • returned average temperature. Handle possible exceptions in main function

-

class TemperatureFile:
    def __init__(self, filename):
        self.__filename = filename

    def getFilename(self):
        return self._Filename

    def setFilename(self):
        self._filename = filename

    def calculateAverage(self):
        try:
            for line in temperatureFile:
                amount = float(line.rstrip("\n"))
                total += amount
                temp = temp + 1
            average = total/temp
            print(average)
        except ValueError as err:
            print(err)
        except IOError as err:
            print(err)
        else:
            average = total/temp
            print(average)
        finally:
            temperatureFile.close() 


def main():
    num1 = 35
    num2 = 63
    num3 = 40
    total = 0.0
    temp = 0.0
    average = 0.0
    temperatureFile = open('Temperatures.txt', 'w')
    temperatureFile.write(str(num1) + '\n')
    temperatureFile.write(str(num2) + '\n')
    temperatureFile.write(str(num3) + '\n')
    temperatureFile.close()
    Temperatures = TemperatureFile('Temperatures.txt')
    temperatureFile = open('Temperatures.txt', 'r')
    calculateAverage(temperatureFile)


main()

I keep receiving an error File "C:\Python27\temp.py", line 49, in main calculateAverage(temperatureFile) NameError: global name 'calculateAverage' is not defined

I'm wondering if i did this right at all or if i was on the right track and how to fix it

ryachza
  • 4,460
  • 18
  • 28
AmbieGirl
  • 119
  • 1
  • 7
  • 7
    Why would you tag `java` and `c++` for this question? Don't spam tags for visibility. It will only attract people that are not interested in your question. – François Andrieux Oct 25 '17 at 18:38
  • 2
    @FrançoisAndrieux to get downvotes more quickly? – Robert Columbia Oct 25 '17 at 18:39
  • i tried temperatureFile.calculateAverage() and it gave me this error temperatureFile.calculateAverage() AttributeError: 'file' object has no attribute 'calculateAverage' – AmbieGirl Oct 25 '17 at 18:46
  • 1
    @AmbieGirl `temperatureFile` is a file handle; `Temperatures` here is an instance of the class, so it would be `Temperatures.calculateAverage()`. – ryachza Oct 25 '17 at 19:00

2 Answers2

2

I think the smallest set of changes that will make this work is:

class TemperatureFile:
    def __init__(self, filename):
        self.__filename = filename

    def getFilename(self):
        return self._Filename

    def setFilename(self):
        self._filename = filename

    def calculateAverage(self):
        try:
          with open(self.__filename,'rb') as temperatureFile:
            total = 0
            temp = 0
            for line in temperatureFile:
                amount = float(line.rstrip("\n"))
                total += amount
                temp = temp + 1
            average = total/temp
            print(average)
        except ValueError as err:
            print(err)
        except IOError as err:
            print(err)
        else:
            average = total/temp
            print(average)
        finally:
            temperatureFile.close() 


def main():
    num1 = 35
    num2 = 63
    num3 = 40
    total = 0.0
    temp = 0.0
    average = 0.0
    temperatureFile = open('Temperatures.txt', 'w')
    temperatureFile.write(str(num1) + '\n')
    temperatureFile.write(str(num2) + '\n')
    temperatureFile.write(str(num3) + '\n')
    temperatureFile.close()
    Temperatures = TemperatureFile('Temperatures.txt')
    Temperatures.calculateAverage()



main()

calculateAverage is a member of the TemperatureFile class, so it needs to be called on an instance of this class (Temperatures, here). calculateAverage takes no arguments. The self argument is just an explicit version of the implicit this common in other languages. I moved the opening of the file into the calculateAverage function since otherwise the __filename attribute is pointless. I also had to add total and temp default definitions.

A more reasonable version [I think], though not strictly conforming to the requirements:

import traceback as tb

class TemperatureFile:
  def __init__(self, filename):
    self.filename = filename

  def calculateAverage(self):
    try:
      with open(self.filename,'rb') as temperatureFile:
        total = 0
        temp = 0
        for line in temperatureFile:
          total += float(line.rstrip("\n"))
          temp += 1
        print(total/temp)
    except:
      tb.print_exc()

with open('Temperatures.txt','wb') as output:
  output.write(str(35) + '\n')
  output.write(str(63) + '\n')
  output.write(str(40) + '\n')

TemperatureFile('Temperatures.txt').calculateAverage()

In Python, everything in the root of the file is evaluate/executed by default, so defining a main function seems a bit uncharacteristic. I also don't think getters and setters are as common, though not unheard of, since Python is so dynamic anyway. A couple key takeaways: I would recommend using the traceback.print_exc() function to provide more detailed error messages, and be sure to use with when opening files to properly handle resource cleanup. Otherwise, I just got rid of some redundant variables that made things somewhat noisy.

ryachza
  • 4,460
  • 18
  • 28
  • first, Thank you so much!!! second in this line: try: with open(self.__filename,'rb') as temperatureFile: what does the rb mean : does it mean you are reading the file? – AmbieGirl Oct 25 '17 at 18:55
  • @AmbieGirl Was that a complete statement? Is there something else that would be helpful? – ryachza Oct 25 '17 at 19:00
  • @AmbieGirl `rb` means read mode, binary. I always use `b` because I've had issues with line endings being adjusted in some cases without it. Basically, `rb` will get you **exactly** what's in the file, which is always what I want. – ryachza Oct 25 '17 at 19:06
  • @AmbieGirl All good glad it was helpful. Everyone starts somewhere. Not sure what your prior experience is but you initially got impressively close. – ryachza Oct 25 '17 at 19:24
0

Main() don't know where to find your method, you need to give the class name where the method resides in.

Either move everything out of the class and use the methods or use the following instead to invoke the method.

TemperatureFile.calculateAverage()

A similar question is being answered here

LostCause
  • 151
  • 1
  • 11