【问题标题】:Programming a function that saves and returns values in python在python中编写一个保存和返回值的函数
【发布时间】:2016-09-21 11:12:50
【问题描述】:

我目前正在尝试使用 Python 并编写一些文本冒险游戏。在我的游戏中,玩家具有某些属性,例如 hp、攻击伤害和物品的库存槽位。 我希望能够在我的代码中的任何地方调用这些属性。为此,我创建了一个接收三个值的函数:

“edit”:指定是否应该编辑变量

“info_id”:指定应该访问哪个变量

“value”:变量的新值

这就是我的代码中的样子:

def player_info(edit, info_id, value):

  if edit == 1:
  ##function wants to edit value
      if info_id == 1:
          player_hp = value
          print ("Assigned hp to: ", player_hp) 
          ##the "prints" are just to check if the asignments work -> they do
          return player_hp

      elif info_id == 2:
          player_attack = value
          print ("Assigned attack to: ", player_attack)
          return player_attack
      elif info_id == 3:
          item_1 = value
          return item_1
      elif info_id == 4:
          item_2 = value
          return item_2
       elif info_id == 5:
          item_3 = value

  elif edit == 0:
  ##function wants to retrieve value
      if info_id == 1:
          return player_hp
      elif info_id == 2:
          return player_attack
      elif info_id == 3:
          return item_1
      elif info_id == 4:
          return item_2
      elif info_id == 5:
          return item_3

实际上有 10 个物品栏位(直到 info_id==13),但它们都一样。

我在代码开头定义了所有变量:

  player_info(1,1,20)
  player_info(1,2,5)
  n=3
  while n<=13:
      player_info(1,n,0)
      n=n+1
##items are not fully implemented yet so I define the item slots as 0

定义有效,我可以说是因为我在代码中实现了控制“打印”。仍然当我调用变量时,例如像这样的健康:

player_info(0,1,0)

我收到一个错误:

local variable 'player_hp' referenced before assignment

函数没有正确保存变量吗?或者是什么问题?

有没有更好的方法来保存变量?在这种情况下,全局变量是要走的路吗?

感谢您的帮助!

【问题讨论】:

  • 请格式化您的代码。缩进是一团糟
  • 您的函数正在创建名为player_hp 等的局部变量,它不会修改同名的全局变量。您可以使用 global 关键字使函数修改全局变量,但创建一个 Player 类并使用该类的实例会更好存储玩家信息。

标签: python function variables save call


【解决方案1】:

首先,您的错误是由于检索未分配的变量而引起的 - 这只是行不通。当您编辑player_hp 时,它不会存储在任何地方。您将它返回给调用它的函数,而不是将它分配给任何东西。它只是迷路了。

其次,你真的应该缩进 4 个空格(或制表符)——它比 2 个空格更易读。不仅为您,也为任何试图提供帮助的人。

最后,解决这个问题的正确方法是学习课程。全局变量不应该在python中使用,只有在特殊情况下,或者在你学习的时候,直接跳到课堂。

你应该创建类似的东西

class Player:

    def __init__(self):
        self.hp = 20  # or another starting hp
        self.attack = 3  # or another starting attack
        self.inventory = []

然后你可以创建一个 Player 类的实例并将它传递给相关的函数

player1 = Player()
print(player1.hp) # Prints out player's hp
player1.hp -= 5  # Remove 5 hp from the player. Tip: Use method to do this so that it can check if it reaches 0 or max etc.
player1.inventory.append("axe")
print(player1.inventory[0]) #  Prints out axe, learn about lists, or use dictionary, or another class if you want this not to be indexed like a list

【讨论】:

    【解决方案2】:

    你问,“函数没有正确保存变量吗?

    一般来说,Python 函数不会保存它们的状态。使用yield 语句的函数例外。如果你写一个这样的函数

    def save_data(data):
        storage = data
    

    然后这样称呼它

    save_data(10)
    

    以后您将无法获得storage 的值。在 Python 中,如果您需要保存数据并稍后检索,您通常会使用classes

    Python classes 允许你做这样的事情:

    class PlayerData(object):
        def __init__(self, hp=0, damage=0):
            self.hp = hp
            self.damage = damage
            self.inventory = list()
            self.max_inventory = 10
    
        def add_item(self, item):
            if len(self.inventory) < self.max_inventory:
                self.inventory.append(item)
    
        def hit(self, damage):
            self.hp -= damage
            if self.hp < 0:
                self.hp = 0
    
        def attack(self, other):
            other.hit(self.damage)
    
    if __name__ == '__main__':
        player1 = PlayerData(20, 5)
        player2 = PlayerData(20, 5)
        player1.attack(player2)
        print player2.hp
        player1.add_item('sword')
        player1.add_item('shield')
        print player1.inventory
    

    输出

    15
    ['sword', 'shield']
    

    这实际上只是触及了如何使用classes 的皮毛。在更完整的实现中,您可能有一个Item 基类。然后你可以创建继承自ItemSwordShield 类。

    【讨论】:

    • 感谢您提供的精彩示例!我将更多地研究课程,它们很棒!
    猜你喜欢
    • 2016-06-29
    • 2022-11-22
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多