编写一个函数,将 returns 值保存在 python 中

Programming a function that saves and returns values in python

我目前正在试验 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

定义有效,我可以判断是因为我在代码中实现了控件 "print"。还是当我调用变量时,例如这样的健康:

player_info(0,1,0)

我得到一个错误:

local variable 'player_hp' referenced before assignment

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

有没有更好的保存变量的方法?在这种情况下,全局变量是可行的方法吗?

感谢您的帮助!

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

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

最后,解决这个问题的正确方法是了解 classes。全局变量不应该在 python 中使用,只有在特殊情况下,或者当你正在学习时,才可以直接跳到 class.

你应该创建类似

的东西
class Player:

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

然后您可以创建一个 Player 实例 class 并将其传递给相关的函数

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

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

一般来说,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 基础 class。然后你可以创建继承自 Item.

SwordShield classes