繁体   English   中英

当调用外部方法时,嵌套在方法中的Python字典会自动执行所有值(方法)

[英]Python dictionary nested within method auto-executes all values (methods) when outer method is called

我正在为游戏开发一个简单的框架,并且为了尝试变得更“ Pythonic”,我正在使用对象/类/字典来尝试捕获我的所有动作/行为(作为函数的方法,等等)。 )。

由于某种原因,每次我在“ Player”类中执行“ act”方法时,act中嵌入的词典都会运行其所有值(这些值又是“ Player”类的同一实例中的方法) 。 换句话说,在提示之前,玩家每次都选择“攻击,治愈和逃跑”。

我敢肯定有一个简单的解释,但是我一直在找几个小时,找不到另一个人的字典自动运行其中所有嵌入方法的示例。 你能帮我吗?

谢谢! -杰克

from random import randint

### BEGIN ALL CLASSES HERE

# To be used for all game objects (living and non-living)
class gameObject(object):
    def __init__(self, name):
        self.name = name

# To be used for all characters who can act in some way/be killed/change
class livingThing(gameObject):
    def __init__(self, name, HP=1):
        self.name = name
        self.HP = HP

# The playable character(s)
class Player(livingThing):

    def __init__(self,name="The Stranger", HP=4, MP=5, strength=1, intellect=1, spirit=1, luck=5, gil=6):
        self.name = name
        self.HP = HP
        self.MP = MP
        self.gil = gil
        self.strength = strength
        self.intellect = intellect
        self.spirit = spirit
        self.luck = luck

    def act(player, enemy):
        actions = {
        "attack" : player.attack(enemy), 
        "heal" : player.heal(enemy), 
        "flee" : player.flee()
        }
        #Takes input from the player

        decision = input("What would you like to do? ")

        if decision.lower() in actions:
            actions[decision.lower()]
        else:
            print("That didn't work!  Try again.")

    # Prints both player and enemy HP
    def printHP(player, enemy):
        print("{0}'s' HP: {1} \n{2}'s HP: {3}".format(player.name, player.HP, enemy.name, enemy.HP))

    # Allows the player to attack an enemy (currently functional)
    def attack(player, enemy):
        enemy.HP -= player.strength
        print("You strike {0} for {1} damage!".format(enemy.name, player.strength))
        player.printHP(enemy)

    # Allows the player to heal a certain amount of health based on its "spirit" stat (currently functional)
    def heal(player, enemy):
        healed = randint(0, player.spirit)
        player.HP += healed
        print("You've healed for {0}!".format(healed))
        player.printHP(enemy)

    #Allows the player to attempt to run away
    def flee(player):
        randluck = randint(0, player.luck)
        if randluck > 3:
            print("You successfully escaped!")
            return player.HP
        else:
            print("You weren't able to escape!")


# Anything that can act with/against the player
class Actor(livingThing):
    def __init__(self, name="Unknown Entity", HP=10, MP=2, gil=3):
        self. name = name
        self.HP = HP
        self.MP = MP
        self.gil = gil

### END ALL CLASSES ###


### DICTIONARIES CONTAINING ACTIONS ###



### CHARACTERS ###

fighter = Player()

monster = Actor()




fighter.act(monster)

我看到了问题。 当您执行Python代码并拥有字典时,Python将对字典进行全面评估。 如果希望将值(在key:value中)对作为这些方法的结果 ,那么这无疑是一种方法。

在您的情况下,您可以做的是引用函数本身,而不是调用它。 您可以通过去除括号来做到这一点,如下所示:

player.attack

代替

player.attack()

然后,要调用该函数,您可以执行以下操作

actions[decision.lower()](enemy)

由于您的功能之一flee不接受任何参数,因此可以为flee提供一个您根本不会在该功能中使用的参数。 如果你在设计很多很多方法,你的播放器能够用行动 ,那么一个策略是给他们都只是命名的参数,如下所示:

def f1(enemy=None,something=None,foo=None):
    if enemy is None:
         raise Exception("enemy cannot be None")
    #process_enemy

但是,如果您还有大量参数,则可以执行以下操作:

def attack(**kwargs):
    #kwargs is a dictionary of parameters provided to the function
    enemy = kwargs.get('enemy',None)
    if enemy is None:
        raise Exception("enemy cannot be None")

def eat(**kwargs):
    food = kwargs.get('food',None)
    if enemy is None:
        raise Exception("food cannot be None")

attack(enemy="someenemyobject")
eat(food="somefoodobject")

attack()                        # raises Exception
attack(food="somefoodobject")   # raises Exception
food(enemy="someenemyobject")   # raises Exception
food(food="somefoodobject",enemy="someenemyobject") # does not raise Exception

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM