Python类和方法

时间:2014-04-15 20:08:56

标签: python class methods

我有python编程的在线练习题。我坚持这个问题:

Write the definition of a class WeatherForecast that provides the following behavior (methods):
A method called set_skies that has one parameter, a String.
A method called set_high that has one parameter, an int.
A method called set_low that has one parameter, an int.
A method called get_skies that has no parameters and that returns the value that was last used as an argument in set_skies .
A method called get_high that has no parameters and that returns the value that was last used as an argument in set_high .
A method called get_low that has no parameters and that returns the value that was last used as an argument in set_low .
No constructor need be defined. Be sure to define instance variables  as needed by your "get"/"set" methods. 

我有这个答案,但我不知道问题是什么。它一直告诉我某处的价值不正确。

class WeatherForecast (object):
    def __init__ (self):
        self.skies = ''
        self.high = ''
        self.low  = ''
    def set_skies (self, value):
        self.skies = value
    def set_high (self, value):
        self.high = value
    def set_low (self):
        self.low = low
    def get_skies (self):
        return self.skies
    def get_high(self):
        return self.high
    def get_low(self):
        return self.low

4 个答案:

答案 0 :(得分:5)

您无法定义skieshighlow

也许在你set事物的函数中,你的意思是:

def set_high (self, value):  # Do this for all setting functions.
    self.high = value  # value is defined, so will work.

答案 1 :(得分:1)

问题很可能是高和低应该是整数。

class WeatherForecast:
    def __init__(self):
        self.__skies=""
        self.__high=0
        self.__low=0

    def set_skies(self, skies):
        self.__skies=skies

    def set_high(self,high):
        self.__high=high

    def set_low(self,low):
        self.__low=low

    def get_skies(self):
        return self.__skies

    def get_high(self):
        return self.__high

    def get_low(self):
        return self.__low

答案 2 :(得分:0)

例如,在此方法中:

def set_high(self, value):    
    self.high = high

您正尝试将分配给 self.high ,但您没有说明的来源,程序只有名为 value 的变量。所以你应该这样改变:

def set_high(self, high):
    self.high = high

答案 3 :(得分:0)

我相信你在set_low中缺少一个参数。

def set_low (self, value):
    self.low = value