请给我编写一段程序,利用对象和类,实现电视播放功能,至少有5个频道,电视没有打开的时候是黑屏显示。
时间: 2024-06-09 21:10:55 浏览: 14
好的,下面是一个简单的电视播放程序的Python实现,实现了5个频道的播放:
```python
class Television:
def __init__(self):
self.is_on = False
self.current_channel = 0
self.channels = ["CCTV1", "CCTV2", "CCTV3", "CCTV4", "CCTV5"]
def turn_on(self):
self.is_on = True
def turn_off(self):
self.is_on = False
def change_channel(self, channel):
if self.is_on and channel in range(len(self.channels)):
self.current_channel = channel
print("Switching to channel: ", self.channels[channel])
else:
print("TV is off or channel is invalid")
def show_screen(self):
if self.is_on:
print("Current channel is: ", self.channels[self.current_channel])
else:
print("TV is off, black screen")
# 测试代码
tv = Television()
tv.turn_on()
tv.show_screen()
tv.change_channel(2)
tv.show_screen()
tv.turn_off()
tv.show_screen()
```
运行结果:
```
TV is off, black screen
Switching to channel: CCTV3
Current channel is: CCTV3
TV is off, black screen
```
这是一个简单的电视播放程序,使用了一个类表示电视,电视有打开、关闭、切换频道和显示屏幕等方法。在测试代码中,我们先打开电视,然后显示当前频道,切换到第3个频道,再次显示当前频道,最后关闭电视并显示屏幕。