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

访问函数中创建的python对象,函数外部,python,python-3.x,scope,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) e

我不知道是否有办法做到这一点。我试图仅在满足特定条件时创建对象。 我可以用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))
我的问题是目前无法使用随机生成的对象。
有什么想法吗?

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

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
def dm_roll():
roll=random.randint(1,20)
打印(卷)
如果掷骰>0,掷骰10,掷骰16,掷骰)#根据可能的条件创建英雄对象
回归英雄
如果_name__=“_main__”:
对手=dm_roll()#返回怪物对象
打印(“您遇到了{}!”格式(对手名称))
hero=createHero()#返回hero对象
战斗(对手、英雄)#让他们战斗

不必要地使用全局变量不是一个好的做法。您应该返回您可能需要的任何对象,不要使用全局变量
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