python - Python在定义时部分确定参数的解决方法?
问题描述
我一直在开发一个基于卡片的战斗游戏来练习 Python 编码,并且我有玩家和卡片的对象。我一直在使用 functools.partial 在创建每个卡片对象时为其分配一个能力,到目前为止,它的工作方式如下:
from functools import partial
class Player(object):
def __init__(self):
self.health = 100
def play_card(self, card):
card.ability(player=self)
human = Player()
computer = Player()
human.opponent = computer
computer.opponent = human
class Card(object):
def __init__(self, ability):
self.ability = ability
def attack(amount, player):
player.opponent.health -= amount
working_card = Card(partial(attack, 8))
human.play_card(working_card)
这显然是代码的一个大大简化的版本,但它是重要的部分。当我调用human.play_card(working_card) 时,人类Player 对象执行函数play_card(card=working_card),然后激活working_card.ability() 部分函数,启动attack(amount=8, player=human) 函数。
但随后我引入了一个变量作为偏函数的参数之一,如下所示:
broken_card = Card(partial(attack, player.health))
human.play_card(broken_card)
部分函数试图确定第一次创建 Card 对象时 player.health 的值,此时它不知道“玩家”是什么。我希望它在调用 attack(amount, player) 时确定 player.health 的值,即“玩家”有意义的时候。我曾尝试使用 lambda 并将 attack() 函数放置在 Card 对象中,但没有成功,我在 Internet 上找不到此类问题的任何答案。我需要一些方法来解决部分尝试在第一次调用 player.health 时确定它,如果不是通过重组我的代码逻辑工作方式来明确地确定它。
解决方案
您可以使用lambda
而不是partial
推迟参数的评估:
broken_card = Card(lambda *args, **kwargs: attack(player.health, *args, **kwargs))
请记住,player
它必须在与定义 this 的范围相同的范围内可用lambda
。然而。由于player
恰好是 的第二个参数attack
,您可以lambda
利用已知参数:
broken_card = Card(lambda player: attack(player.health, player))
推荐阅读
- python - TypeError:使用 numpy 和 pydicom 对 0-d 数组进行迭代
- python - 将 pandas 列编码为分类值
- javascript - 同名的多个 Select 选项
- java - 如何让我导入的 Excel 电子表格填充 JTable?
- postgresql - Postgresql - 24 小时滚动窗口
- r - 如何在 R 中取两列并将它们展平,如下所示?
- google-apps-script - 谷歌脚本循环
- ethereum - Solidity - Truffle:错误:处理事务时出现 VM 异常:操作码无效,不是因为还原
- javascript - 如何将数组传递给函数,然后调用它 - javascript
- python - 如何正确获取具有 Retry-After 限制的 API