You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于类实例属性跳过方法执行?TV类功能异常修复求助

解决电视关闭时仍可修改音量和频道的问题

问题出在当前的Television类中,调节频道、音量的方法没有校验电视是否处于开机状态(status为True),所以即使电视关机,这些操作依然会生效。只需要在对应的方法开头添加状态判断即可解决。

修改后的完整代码如下:

class Television:
    min_volume = 0
    max_volume = 2
    min_channel = 0
    max_channel = 3

    def __init__(self):
        self.status = False
        self.muted = False
        self.volume = Television.min_volume
        self.channel = Television.min_channel

    def power(self):
        self.status = not self.status

    def mute(self):
        # 电视关机时静音操作无效
        if not self.status:
            return
        self.muted = not self.muted

    def channel_up(self):
        # 电视未开机时不执行频道上调
        if not self.status:
            return
        self.channel += 1
        if self.channel > Television.max_channel:
            self.channel = Television.min_channel

    def channel_down(self):
        # 电视未开机时不执行频道下调
        if not self.status:
            return
        self.channel -= 1
        if self.channel < Television.min_channel:
            self.channel = Television.max_channel

    def volume_up(self):
        # 电视未开机时不执行音量上调
        if not self.status:
            return
        self.volume += 1
        if self.volume > Television.max_volume:
            self.volume = Television.max_volume

    def volume_down(self):
        # 电视未开机时不执行音量下调
        if not self.status:
            return
        self.volume -= 1
        if self.volume < Television.min_volume:
            self.volume = Television.min_volume

    def __str__(self):
        return f"TV Status: Power = {self.status}, Channel = {self.channel}, Volume = {self.volume}"

修改说明

  • 所有涉及频道、音量调整的方法(channel_up、channel_down、volume_up、volume_down)开头都添加了if not self.status: return,电视关机时直接终止方法执行,不修改对应参数
  • 额外给mute方法也添加了状态判断,因为电视关机时静音操作没有实际意义,符合真实场景逻辑

内容的提问来源于stack exchange,提问作者user21083709

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:05:02