Python基础(③嵌套和逻辑代码)

123

import time
from enum import Enum
from typing import List, Dict, Any

class ComponentType(Enum):
    UNIT = "UNIT"
    LOGIC = "LOGIC"
    SLEEP = "SLEEP"  # 新增睡眠类型

class LogicType(Enum):
    FOR_LOOP = "FOR_LOOP"
    SLEEP = "SLEEP"

# 自定义模拟数据库
class MockDatabase:
    def __init__(self):
        self.components = {
            # 单元组件
            "unit1": {
                "type": ComponentType.UNIT,
                "x": 100,
                "y": 200,
                "description": "点击登录按钮"
            },
            "unit2": {
                "type": ComponentType.UNIT,
                "x": 300,
                "y": 400,
                "description": "点击提交按钮"
            },
            # 睡眠组件
            "sleep1": {
                "type": ComponentType.SLEEP,
                "duration": 2,
                "description": "操作间隔等待"
            },
            # 逻辑组件(包含多个嵌套组件)
            "loop1": {
                "type": ComponentType.LOGIC,
                "logic_type": LogicType.FOR_LOOP,
                "loop_count": 2,
                "nested_components": ["unit1", "unit2", "sleep1"]  # 支持多组件嵌套
            }
        }

    def get_component(self, component_id: str) -> Dict[str, Any]:
        return self.components.get(component_id, {})

class WorkflowEngine:
    def __init__(self):
        self.db = MockDatabase()
        self.execution_count = 0

    def execute_workflow(self, workflow: List[str]):
        """执行工作流"""
        print("🚀 开始执行工作流")
        for component_id in workflow:
            self._execute_component(component_id)   #组件id loop1
        print("\n✅ 工作流执行完成")
        print(f"📊 总执行次数: {self.execution_count}")

    def _execute_component(self, component_id: str):      #执行流程
        """执行单个组件(支持递归调用)"""
        component = self.db.get_component(component_id)
        print("component_id",component_id) #unit1  
        print("component",component)   #component {'type': <ComponentType.UNIT: 'UNIT'>, 'x': 100, 'y': 200, 'description': '点击登录按钮'} 
        if not component:
            print(f"⚠ 找不到组件: {component_id}")
            return

        # 打印当前执行的组件
        comp_type = component["type"].value
        print(f"\n🔧 [{comp_type}] 执行组件: {component_id}")

        if component["type"] == ComponentType.UNIT:
            self._execute_unit(component)
        elif component["type"] == ComponentType.LOGIC:
            self._execute_logic(component)
        elif component["type"] == ComponentType.SLEEP:
            self._execute_sleep(component)

    def _execute_unit(self, unit: Dict[str, Any]):
        """执行单元操作"""
        print(f"   🖱 模拟点击: {unit['description']}")
        print(f"     坐标: ({unit['x']}, {unit['y']})")
        print(f"     操作完成!")
        time.sleep(0.3)
        self.execution_count += 1

    def _execute_logic(self, logic: Dict[str, Any]):
        """处理逻辑组件"""
        if logic["logic_type"] == LogicType.FOR_LOOP:
            print("logic",logic)   #{'type': <ComponentType.LOGIC: 'LOGIC'>, 'logic_type': <LogicType.FOR_LOOP: 'FOR_LOOP'>, 'loop_count': 2, 'nested_c
            self._execute_for_loop(logic)
            

    def _execute_for_loop(self, logic: Dict[str, Any]): 
        """执行FOR循环"""
        loop_count = logic["loop_count"]
        print(f"   🔄 开始FOR循环 (次数: {loop_count})")
        
        for i in range(loop_count):
            print(f"     ♻ 第 {i+1}/{loop_count} 次循环开始")
            # 执行所有嵌套组件
            for nested_id in logic["nested_components"]:
                self._execute_component(nested_id)
            print(f"     ✓ 第 {i+1}/{loop_count} 次循环结束\n")
            time.sleep(0.2)

    def _execute_sleep(self, sleep: Dict[str, Any]):
        """执行睡眠组件"""
        duration = sleep["duration"]
        print(f"   ⏳ 开始休眠: {sleep['description']}")
        print(f"     持续时间: {duration}秒")
        time.sleep(duration)
        print(f"     ✓ 休眠完成!")

if __name__ == "__main__":
    # 定义工作流流程: loop1 -> unit1 -> loop1 -> unit2
    workflow_sequence = ["loop1", "unit1", "loop1", "unit2"]
    
    # 创建并执行引擎
    engine = WorkflowEngine()
    engine.execute_workflow(workflow_sequence)

拆分解析

import time
from enum import Enum
from typing import List, Dict, Any

class ComponentType(Enum):
    UNIT = "UNIT"
    LOGIC = "LOGIC"
    SLEEP = "SLEEP"  
 
class LogicType(Enum):
    FOR_LOOP = "FOR_LOOP"
    SLEEP = "SLEEP"


class MockDatabase:
    def __init__(self):
        self.components = {
            # 单元组件
            "unit1": {
                "type": ComponentType.UNIT,
                "x": 100,
                "y": 200,
                "description": "点击登录按钮"
            },
            "unit2": {
                "type": ComponentType.UNIT,
                "x": 300,
                "y": 400,
                "description": "点击提交按钮"
            },
            # 睡眠组件
            "sleep1": {
                "type": ComponentType.SLEEP,
                "duration": 2,
                "description": "操作间隔等待"
            },
            # 逻辑组件(包含多个嵌套组件)
            "loop1": {
                "type": ComponentType.LOGIC,
                "logic_type": LogicType.FOR_LOOP,
                "loop_count": 2,
                "nested_components": ["unit1", "unit2", "sleep1"]  # 支持多组件嵌套
            }
        }
 
    def get_component(self, component_id: str) -> Dict[str, Any]:
        return self.components.get(component_id, {})

print(MockDatabase())
db=MockDatabase()
print(db)
print(db.get_component("unit1"))

123

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aaiier

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值