如何调用__init__函数内的函数?

时间:2017-11-03 18:56:52

标签: python python-3.x

我的教授希望我们为这个名为loadtemperatureData的程序添加一个新功能。

  • 此函数使用循环将温度文件(文件名)中的温度加载到列表中,并将列表返回给调用者。

她还希望我们修改__init__功能:

修改__init__函数以再添加一个数据属性temperatureList。在__init__内部,调用loadTemperatureData函数并将返回的值分配给temperatureList

修改calculateAverage函数以使用数据属性temperatureList来计算平均温度。

主要功能保持不变。我一直收到这个错误:

File "C:/Users/abrooks3/Downloads/temperatureadd.py", line 57, in main
Temperatures = TemperatureFile('Temperatures.txt')
TypeError: __init__() missing 1 required positional argument: 'temperatureList'

这是我的代码: 我原来的代码在底部,我不知道她想要什么,或者我是否试图正确地做到这一点

class TemperatureFile:
    def __init__(self, filename, temperatureList):
        self.__filename = filename
        self.temperatureList = []
        self.loadTemperatureData(temperatureList)


    def getFilename(self):
        return self._Filename

    def setFilename(self):
        self._filename = filename

    def calculateAverage(self, temperaturelist):
        try:
           with open(self.__filename,'r') as temperatureFile:
            total = 0
            temp = 0
            for line in temperatureFile:
                amount = float(line.rstrip("\n"))
                total += amount
                temp = temp + 1
            average = total/temp

        except ValueError as err:
            print(err)
        except IOError as err:
            print(err)
        else:
            average = total/temp
            print(average)
        finally:
            temperatureFile.close()

        def loadTemperatureData(self, filename):
            with open(self.__filename,'w') as temperartureFile:
                temps = [35, 63, 40]
                for temp in temps:
                    temperatureFile.write(str(temp)+ 'n')
                temeperatureFile.close
                return temps


    def main(): 
        num1 = 35
        num2 = 63
        num3 = 40
        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(temperatureList)

    main()


##MY original code
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,'r') as temperatureFile:
            total = 0
            temp = 0
            for line in temperatureFile:
                amount = float(line.rstrip("\n"))
                total += amount
                temp = temp + 1
            average = total/temp

        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
    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()

4 个答案:

答案 0 :(得分:1)

以下是修改过的代码:

class TemperatureFile:
    def __init__(self, filename):
        self.temperatureList = self.loadTemperatureData(filename)  # The __init__requirement (this line). But it doesn't make sense to assign a method's return to a member, when that member could be easily set from within the method


    def calculateAverage(self):  # The calculateAverage requirement
        if not self.temperatureList:
            return None
        #return sum(self.temperatureList) / len(self.temperatureList)
        temp_sum = 0
        for temp in self.temperatureList:
            temp_sum += temp
        return temp_sum / len(self.temperatureList)

    def loadTemperatureData(self, filename):  # The loadTemperatureData requirement (whole function)
        temps = list()
        with open(filename, "r") as temperartureFile:
            for line in temperartureFile.readlines():
                temps.append(float(line.strip()))
        return temps


def main(): 
    num1 = 35
    num2 = 63
    num3 = 40
    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")
    print(Temperatures.calculateAverage())

main()

备注

  • 我剥离了很多旧的(未使用过的)代码
  • 来自return的评论calculateAverage行是其下方4行的简化形式。您可以取消注释并删除以下4行
  • main,而不是num1num2,...您可以创建一个列表:temperatures = [35, 63, 40],然后迭代它:{{1} },for temperature in temperatures:。它更优雅,如果你想添加另一个温度,你只需在列表中添加一个新元素

<强>输出

temperatureFile.write(str(temperature) + "\n")

答案 1 :(得分:0)

您修改了__init__以获取2个参数(不计算self);正如错误所说,你只用1来调用它。

答案 2 :(得分:0)

您不需要将temperatureList参数包含在构造函数中 - 无论该参数的值如何,您都要将loadTemperatureData()的返回值分配给它,所以你可以完全丢弃它。

在不相关的说明中,我认为您希望将<{1}}的返回值分配给self.loadTemperatureData(filename),以便它看起来像

temperatureList

此外,您的def __init__(self, filename): self.__filename = filename self.temperatureList = self.loadTemperatureData(self.__filename) 是在另一个函数中定义的 - 因此,如果您的课程实际上看起来像是您在问题中包含的课程,那么此代码将无法使用。

答案 3 :(得分:0)

当您使用一个参数创建一个对象时,您的构造函数被声明为2个参数。

您可以删除第二个参数:

def __init__(self, filename):
        self.__filename = filename
        self.temperatureList = []
        self.loadTemperatureData(filename)