我在制作一个模拟电视

1 投票
2 回答
2798 浏览
提问于 2025-04-15 20:44

我需要做一个电视机,它可以显示频道和音量,并且能告诉用户电视是否开着。我已经写了大部分代码,但不知道为什么频道无法切换。我对属性的使用不太熟悉,我觉得这可能是我遇到的问题。请帮帮我。

class Television(object):

    def __init__(self, __channel=1, volume=1, is_on=0):
        self.__channel=__channel
        self.volume=volume
        self.is_on=is_on

    def __str__(self):
        if self.is_on==1:
            print "The tv is on"
            print self.__channel
            print self.volume
        else:
            print "The television is off."

    def toggle_power(self):
        if self.is_on==1:
            self.is_on=0
            return self.is_on
        if self.is_on==0:
            self.is_on=1
            return self.is_on

    def get_channel(self):
        return channel

    def set_channel(self, choice):
        if self.is_on==1:
            if choice>=0 and choice<=499:
                channel=self.__channel
            else:
                print "Invalid channel!"
        else:
            print "The television isn't on!"

    channel=property(get_channel, set_channel)

    def raise_volume(self, up=1):
        if self.is_on==1:
            self.volume+=up
            if self.volume>=10:
                self.volume=10
                print "Max volume!"
        else:
            print "The television isn't on!"

    def lower_volume(self, down=1):
        if self.is_on==1:
            self.volume-=down
            if self.volume<=0:
                self.volume=0
                print "Muted!"
        else:
            print "The television isn't on!"

def main():

    tv=Television()
    choice=None
    while choice!="0":
        print \
        """
        Television

        0 - Exit
        1 - Toggle Power
        2 - Change Channel
        3 - Raise Volume
        4 - Lower Volume
        """

        choice=raw_input("Choice: ")
        print

        if choice=="0":
            print "Good-bye."

        elif choice=="1":
            tv.toggle_power()
            tv.__str__()

        elif choice=="2":
            change=raw_input("What would you like to change the channel to?")
            tv.set_channel(change)
            tv.__str__()

        elif choice=="3":
            tv.raise_volume()
            tv.__str__()

        elif choice=="4":
            tv.lower_volume()
            tv.__str__()

        else:
            print "\nSorry, but", choice, "isn't a valid choice."

main()

raw_input("Press enter to exit.")

2 个回答

3

额外提示:

把这个作为社区共享,让大家都能提供想法和建议。

  • 不要用两个下划线开头命名你的属性。这样并意味着它是私有的。如果你想要一个私有的名字,使用一个下划线就可以了。
  • 你其实并没有真正使用你创建的 channel 属性。
  • is_on 中使用 True 和 False,而不是 1 和 0。
  • __str__ 方法应该返回一个字符串,而不是打印一个字符串。而且你不需要直接调用它,只需打印实例,Python 会自动调用这个方法(通常你不需要自己调用以两个下划线开头和结尾的方法)。

使用以上提示的代码:

class Television(object):
    def __init__(self, channel=1, volume=1, is_on=False):
        self._channel= channel
        self.volume = volume
        self.is_on = is_on

    def __str__(self):
        volume = self.volume
        if not volume:
            volume = 'muted'
        elif volume == 10:
            volume = 'max'
        if self.is_on:
            return "The TV is on, channel {0}, volume {1}".format(self.channel, volume)
        else:
            return "The TV is off."

    def toggle_power(self):
        self.is_on = not self.is_on
        return self.is_on

    def get_channel(self):
        return self._channel

    def set_channel(self, choice):
        self._check_on()
        if 0 <= choice <= 499:
            self._channel = choice
        else:
            raise ValueError('Invalid channel')

    channel = property(get_channel, set_channel)

    def _check_on(self):
        if not self.is_on:
            raise ValueError("The television isn't on")

    def raise_volume(self, up=1):
        self._check_on()
        self.volume += up
        if self.volume >= 10:
            self.volume = 10

    def lower_volume(self, down=1):
        self._check_on()
        self.volume -= down
        if self.volume <= 0:
            self.volume = 0

def main():
    tv = Television()
    while True:
        print 'Status:', tv
        print \
        """
        Television

        0 - Exit
        1 - Toggle Power
        2 - Change Channel
        3 - Raise Volume
        4 - Lower Volume
        """
        choice=raw_input("Choice: ")

        try:
            if choice=="0":
                break
            elif choice=="1":
                tv.toggle_power()
            elif choice=="2":
                change=int(raw_input("What would you like to change the channel to? "))
                tv.set_channel(change)
            elif choice=="3":
                tv.raise_volume()
            elif choice=="4":
                tv.lower_volume()
            else:
                raise ValueError("Sorry, but {0} isn't a valid choice.".format(choice))
        except ValueError as e:
            print '\n\n *** ERROR: {0}\n'.format(e)

main()
raw_input("Press enter to exit.")
5
  1. 频道号是整数类型,但 raw_input 返回的是字符串类型。应该改成:

    change = int(raw_input("What would you like to change the channel to?"))
    
  2. 还有你的 set_channel 函数里有这个:

    channel=self.__channel
    

    但应该改成:

    self.__channel = choice
    

这两个改动能让它正常工作。

撰写回答