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

如何用单个函数批量修改所有设备的布尔值?智能家居类实现

实现批量控制智能家居设备的函数

你可以直接在smartHome类中新增turnallonall方法,把循环逻辑封装到类内部,这样就能一次性完成设备状态修改,无需手动逐个传参:

class smartHome():
    def __init__(self):
        self.devices = []
        
    def getDevices(self):
        return self.devices
    
    def getDeviceAt(self,index):
        return self.devices[index]  # 修复原方法缺少return的问题
        
    def addDevice(self,device):
         self.devices.append(device)
    
    def toggleSwitch(self,index):
        self.devices[index].toggle_Switch()

    # 新增批量控制方法
    def turnallonall(self):
        # 遍历所有设备切换状态
        for device in self.devices:
            device.toggle_Switch()
        
        # 如果你只需要控制前3个指定设备(plug1、plug2、smartdoor),可以替换成:
        # for i in range(3):
        #     self.toggleSwitch(i)

说明

  • 封装后的turnallonall方法直接操作类内的devices列表,调用时只需执行smarthome.turnallonall()即可完成批量修改。
  • 修复了getDeviceAt方法的遗漏:原方法没有返回设备对象,补上return后才能正常获取指定索引的设备。
  • 如果你的需求是将设备状态设为开启(而非切换),可以把方法内的device.toggle_Switch()替换为设备类对应的开启方法(比如device.turn_on(),需确保设备类实现了该方法)。

使用示例

# 初始化智能家居实例
smarthome = smartHome()
# 添加目标设备(需提前定义plug1、plug2、smartdoor实例)
smarthome.addDevice(plug1)
smarthome.addDevice(plug2)
smarthome.addDevice(smartdoor)

# 一键批量修改设备状态
smarthome.turnallonall()

内容的提问来源于stack exchange,提问作者Krutarth Mukeshbhai Joshi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:07:22