Skip to main content
 首页 » 编程设计

python之我在做模拟电视

2025年05月04日11xxx_UU

我需要制作一台电视,向用户显示 channel 和音量,并显示电视是否打开。我已经完成了大部分代码,但由于某种原因, channel 不会切换。我对属性的工作方式相当陌生,我认为这就是我的问题所在。请帮忙。

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.") 

请您参考如下方法:

  1. channel 号是整数,但raw_input返回字符串。应该是:

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

    channel=self.__channel 
    

    什么时候应该:

    self.__channel = choice 
    

这两项更改使其发挥作用。