Я делаю смоделированный телевизор

1

Мне нужно сделать телевизор, показывающий пользователю канал и громкость, и показывает, включен ли телевизор. У меня есть большая часть кода, но по какой-то причине каналы не будут переключаться. Я довольно незнакома с тем, как работают свойства, и я думаю, что моя проблема здесь. Помогите пожалуйста.

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.")
Теги:
class
properties

2 ответа

5
Лучший ответ
  • Номер канала является целым числом, но raw_input возвращает строку. Должно быть:

    change = int(raw_input("What would you like to change the channel to?"))
    
  • также ваша функция set_channel имеет следующее:

    channel=self.__channel
    

    Когда это должно быть:

    self.__channel = choice
    

Эти два изменения заставляют его работать.

3

ДОПОЛНИТЕЛЬНЫЕ СОВЕТЫ: ​​

Проводя это как сообщество wiki, чтобы каждый мог помочь с идеями и подсказками.

  • Не указывайте свои атрибуты, начиная с двух символов подчеркивания. Он не означает закрытый. Если вы хотите получить частное имя, используйте одно подчеркивание.
  • Вы действительно не используете созданный вами ресурс channel.
  • Используйте True и False вместо 1 и 0 для is_on
  • __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.")

Ещё вопросы

Сообщество Overcoder
Наверх
Меню