一位开发者正在尝试模拟一个电视机,其中需要显示当前频道、音量以及电视是否打开。大部分代码已完成,但频道切换功能无法正常工作。该开发者认为问题可能出在属性的使用上,需要解决该问题,使频道能够正常切换。
2、解决方案
-
第一个答案指出,问题在于频道号是整数,但
raw_input
返回的是字符串。因此,需要将raw_input
返回的值显式转换为整数,以便正确设置频道号。此外,set_channel
函数中的channel=self.__channel
语句也需要改为self.__channel = choice
,以正确设置频道号。 -
第二个答案提供了更进一步的修改建议,包括使用
True
和False
代替1
和0
来表示电视机的开关状态,使用单下划线(_
)而不是双下划线(__
)来命名私有属性,将__str__
方法修改为返回字符串而不是直接打印,以及使用raise ValueError
来处理无效的输入。
以下是修改后的代码:
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.")
通过以上解答和修改,电视机模拟器能够正常切换频道,并且提供了更健壮和清晰的代码结构。