基础广播节目输入斗争

时间:2016-04-18 02:49:47

标签: python class oop

我已经在这里工作了好几个小时试图弄清楚要做什么。我似乎无法弄清楚如何处理用户输入,以便激活实例变量并返回一个工作站。

class Radio:

    def __init__(self):
        self.stations = ["STATIC", "97.2", "99.6", "101.7", "105.3", "108.5"]
        self.station_index = 0

    def seekNext(self):
        self.station_index = (self.station_index + 1) % len(self.stations)
        return self.station_index

    def longPressPreset1(self):
        self.progamStation1 = self.stations[self.station_index]

    def longPressPreset2(self):
        self.programStation2 = self.stations[self.station_index]

    def longPressPreset3(self):
        self.programStation3 = self.stations[self.station_index]

    def shortPressPreset1(self):
        self.programStaion1

    def shortPressPreset2(self):
        self.programStation2

    def shortPressPreset3(self):
        self.programStation3

    def displayLCD(self):
        print("Currently Tuned:",self.station_index)
        print("present1:", self.programStation1)
        print("present2:", self.programStation2)
        print("present3:", self.programStation3)

    def __str__(self):
        return "Currently Tuned:", str(self.station_index)


def main():
    myradio = Radio()
    print(myradio)
    displayMenuGetOption()

def displayMenuGetOption():
    print("1 = Display tuned in staion")
    print("2 = Program present station 1")
    print("3 = Program present station 2")
    print("4 = Program present station 3")
    print("5 = Seek next station")
    print("6 = Tune preset station 1")
    print("7 = Tune preset station 2")
    print("8 = Tune preset station 3")
    print("9 = Dump Programming")
    print("10 = Turn off radio")
    option = input("\nEnter option:")

 main()

我正在考虑使用if逻辑,但我认为它会使代码更复杂。我注意到当我试图返回当前的Tuned电台时,我得到了0而不是静态。目前应该调整输出:STATIC。我只想帮助弄清楚我将如何获得用户输入匹配并激活类中的实例变量。

2 个答案:

答案 0 :(得分:0)

使用:

def __str__(self):
    return 'Currently tuned: %s' % self.stations[self.station_index] 

答案 1 :(得分:0)

  • print("Currently Tuned:", self.station_index)打印当前电台的索引,而不是名称。您可能想要print("Currently Tuned:", self.stations[self.station_index])
  • return "Currently Tuned:", str(self.station_index)不返回字符串。您可能想要return "Currently Tuned: {}".format(self.stations[self.station_index]))
  • self.programStaion1中的shortPressPreset1行没有做任何事情。您可能需要return self.programStation1return self.stations[self.programStation1](顺便说一下:错字)。其他两个shortPressPreset方法也是如此。
  • 您未在programStation1中初始化__init__等。如果在shortPressPreset1之前调用displayLCDlongPressPreset1,则该对象没有成员programStation1,并且会引发异常。

如果您不想使用if语句处理用户输入,可以使用字典处理它:

actions = {
    '1': radio.displayLCD,
    '2': radio.longPressPreset1,
    '5': radio.seekNext,
    # ...
}
actions[option]()