首页 > 解决方案 > 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 时确定它,如果不是通过重组我的代码逻辑工作方式来明确地确定它。

标签: pythonpython-3.xfunctools

解决方案


您可以使用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))

推荐阅读