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

时间:2018-03-16 00:26:43

标签: python python-3.x scope

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

这是第一部分。

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生成了一个&#39; Goblin&#39;创建了。我希望能够在另一个函数中使用该对象,如下所示。

def fight():

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

我的问题是我目前无法使用随机生成的对象。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你需要写一个主脚本,你需要传递对手变量,如下所示:

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
相关问题