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

标签 python class dictionary methods instance

我正在为游戏开发一个简单的骨架,为了尝试变得更加“Pythonic”,我正在使用对象/类/字典来 try catch 我所有的 Action /行为(作为方法)功能等)。

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

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

谢谢! - jack

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 会完全评估该字典。如果您希望您的值(在键:值中)对成为这些方法的结果,这肯定是一种方法。

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

player.attack

而不是

player.attack()

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

Action [decision.lower()](敌人)

由于您的函数之一 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

关于当调用外部方法时,嵌套在方法中的Python字典会自动执行所有值(方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54282357/

相关文章:

python - 如何在 django 模板中迭代嵌套字典和列表

python - 如何使用 python 和 matplotlib 将页码添加到 PDF 文件?

Python 类继承 : How to initialize a subclass with values not in the parent class

ruby 。如何知道定义了哪个类的实例方法?

python - urllib3.exceptions.ProtocolError : ('Connection aborted.' ,错误(10054, 'An existing connection was forcibly closed by the remote host'))

python - 使用 pymongo 对同一索引执行多个正则表达式匹配

C++代码改进,数组越界

Python:从字典中添加列表的值和子值

Python 字典 : Needed a better output

Python 以预定义的顺序对 Dict 进行排序