如何通过构造函数参数为Monkey类分配自定义操作与投掷函数?
在Advent of Code第11天中为Monkey实例设置自定义操作和投掷函数
问题描述
我正在解决Advent of Code第11天的题目,输入为4只猴子的物品列表、操作规则、测试条件及投掷目标。我计划创建Monkey类来实现猴子逻辑,但每只猴子的operation和throw函数各不相同,请问能否在创建Monkey实例时为其设置这些自定义函数?
回答
当然可以,这是处理这类多实例差异化逻辑的常用方案,以下是几种实现方式:
直接传入函数对象
Python里函数是一等公民,可以直接把自定义的operation和throw函数作为参数传入Monkey的构造方法,实例保存后按需调用即可。示例代码:class Monkey: def __init__(self, items, operation, throw_func): self.items = items.copy() # 避免外部列表被修改 self.operation = operation self.throw_func = throw_func self.inspect_count = 0 def take_turn(self, monkeys): for item in self.items: self.inspect_count += 1 # 执行自定义的 worry 值操作 new_worry = self.operation(item) # 题目里通常有除以3的缓解步骤 new_worry = new_worry // 3 # 执行自定义投掷逻辑,获取目标猴子索引 target_idx = self.throw_func(new_worry) # 将物品投给目标猴子 monkeys[target_idx].items.append(new_worry) # 清空当前猴子的物品列表 self.items.clear() # 为猴子0定义操作和投掷函数 def monkey0_operation(item): return item * 19 def monkey0_throw(worry): return 2 if worry % 23 == 0 else 3 # 创建猴子实例 monkey0 = Monkey([79, 98], monkey0_operation, monkey0_throw)用lambda表达式简化短逻辑
如果操作或投掷规则比较简短,直接用lambda表达式可以省去单独定义函数的步骤:# 创建猴子1实例 monkey1 = Monkey( items=[54, 65, 75, 74], operation=lambda x: x + 6, throw_func=lambda x: 2 if x % 19 == 0 else 0 )闭包封装带状态的复杂逻辑
如果投掷逻辑需要依赖额外参数(比如测试用的除数、命中/未命中的目标猴子),可以用闭包封装这些状态:def make_throw_func(divisor, true_target, false_target): def throw_func(worry): return true_target if worry % divisor == 0 else false_target return throw_func # 为猴子2生成投掷函数 monkey2_throw = make_throw_func(divisor=13, true_target=1, false_target=3) monkey2 = Monkey( items=[79, 60, 97], operation=lambda x: x * x, throw_func=monkey2_throw )
这种设计能让Monkey类保持通用性,同时完美适配每只猴子的独特规则,代码简洁且易于扩展维护。
内容的提问来源于stack exchange,提问作者Dark
相关产品推荐
相关产品推荐

