访问函数外部创建的python对象

Accessing python objects created in function, outside of function

本问题已经有最佳答案,请猛点这里访问。

我不知道有没有办法做到这一点。我正试图创建一个对象,只有在满足某个条件时。我可以用if语句创建对象,但不知道如何在以后的代码中使用它。我应该使用"global"吗?我不确定,因为如果每个if/elif语句都使用相同的对象名。

这是第一部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
def dm_roll():
  roll = random.randint(1, 20)
  print(roll)
  if roll > 0 and roll <= 10:
    opponent = Monster('Goblin', 6, 2)
  elif roll > 10 and roll <= 16:
    opponent = Monster('Zombie', 8, 3)
  elif roll > 16 and roll <= 19:
    opponent = Monster('Ogre', 15, 5)
  else:
    opponent = Monster('Dragon', 1000000, 10)

  print("You have run into a {}!".format(opponent.name))

所以在这里我会创建一个基于随机数生成器的对象。假设生成了一个3,并创建了一个"地精"。我希望能够在下面的函数中使用该对象。

1
2
3
4
5
def fight():

  while opponent.alive() and hero.alive():
    hero.print_status()
    opponent.print_status()

我的问题是我目前不能使用随机生成的对象。有什么主意吗?


您需要编写一个主脚本,在其中传递opponent变量,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def dm_roll():
  roll = random.randint(1, 20)
  print(roll)
  if roll > 0 and roll <= 10:
    opponent = Monster('Goblin', 6, 2)
  elif roll > 10 and roll <= 16:
    opponent = Monster('Zombie', 8, 3)
  elif roll > 16 and roll <= 19:
    opponent = Monster('Ogre', 15, 5)
  else:
    opponent = Monster('Dragon', 1000000, 10)
  return opponent   #you need to return the opponent


def fight(opponent,hero):
  # Takes in the opponent and hero
  while opponent.alive() and hero.alive():
    hero.print_status()
    opponent.print_status()

def createHero():
  hero= Hero("<Hero Parameter">) #create hero object as per the conditions you might have
  return hero

if __name__="__main__":
  opponent = dm_roll() # returns the Monster object
  print("You have run into a {}!".format(opponent.name))
  hero = createHero() #returns the Hero Object
  fight(opponent,hero) #Let them fight