1

好的!基本上,我在一个函数中声明了一个变量,我想在另一个函数中使用该变量。我不想传递参数,因为我觉得会有更简单的方法来做到这一点。这是我的代码:

#!/usr/bin/python

#import os
import time
print ("Hello and welcome to Pygame!")
time.sleep(1)
print ("Would you like to load? (\"Y/N\")")

def LON():
    loadOrNew = raw_input()

    if loadOrNew == "N":
        hp = 100
        strhp = str(hp)
        lvl = 1
        strlvl = str(lvl)
        atk = 5
        stratk = str(atk)
        defn = 2
        strdefn = str(defn)
        fout = open("pygame.dat", "w")
        fout.write (strhp) 
        fout.write("\n")
        fout.write(strlvl)
        fout.write("\n")
        fout.write(stratk)
        fout.write("\n")
        fout.write(strdefn)
        fout.close()
        FIRSTPLAY()
        return

    if loadOrNew == "Y":
        fin = open("pygame.dat", "r")
        hpstr = fin.readline()
        lvlstr = fin.readline()
        atkstr = fin.readline()
        defstr = fin.readline()
        hp = int(float(hpstr))
        lvl = int(float(lvlstr))
        atk = int(float(atkstr))
        defn = int(float(defnstr))
        fin.close()
        return

    if loadOrNew != "Y" and loadOrNew != "N":
        print("Im sorry, what?")
        LON()
        return

    return

def SAVE():
    fout = open("pygame.dat", "w")
    fout.write(hp)
    fout.write(lvl)
    fout.write(atk)
    fout.close(defn)
    return


def FIRSTPLAY():
    print("man/woman?")
    gender = raw_input()
    if gender != "man" and gender != "woman":
        print("Not valid gender.")
        FIRSTPLAY()

    print("KING - ")    
    print(" Young " + gender + ", you are herby my knight!")
    time.sleep(1)
    print(" My daughter, princess PYTHON, has been captured!")
    time.sleep(1)
    print(" You are to find her, and relieve this world of her captor!")
    time.sleep(1)
    print(" Some say this evil man's name is GAMEMAKER, but we really don't know.")
    time.sleep(1)
    print(" What do you think it is?")
    captor = raw_input()
    time.sleep(1)
    print(" So you think it is " + captor + "?")
    time.sleep(1)
    print("     Very well, find " + captor + " ASAP!")
    PLAY()
    return

def PLAY():
    print hp
    print lvl
    print atk
    print defn
    greenSlime(hp, lvl, atk, defn)
    return

def greenSlime(php, plvl, patk, pdefn):
    MHP = 10
    MLVL = 1
    MATK = 2
    MDEF = 2
    print "Green Slime - "
    print " HP: 10"
    print " LVL: 1"
    print " ATK: 2"
    print " DEF: 2"
    print "ATK OR DEF?"

LON()

我想在 PLAY 函数中使用在 LON 函数中声明的 hp、lvl、atk 和 defn 变量。我确信有一种比传递参数更简单的方法。

4

3 回答 3

1

在内部LON(),您可以使用以下global语句:

def LON():
    global hp, lvl, atk, defn

然后,对内部这些变量的赋值LON()将创建全局变量。创建全局变量后,您可以在其他地方使用它们(无需global声明)。请注意,无论您想为全局变量分配新值的任何地方,都需要global在该函数中使用相应的语句。

于 2012-04-21T03:43:10.147 回答
1

仅仅在 global 中声明一个变量是行不通的。global 关键字是要求解释器在为其赋值时不要将其视为本地(覆盖具有相同名称的全局变量)。您需要做的是在应该共享它的函数之上的范围内定义变量。请注意,您不需要在函数中声明一个全局变量以进行只读访问。当解释器在本地范围内找不到变量时,它会自动在外部范围内查找它。但是在赋值语句的情况下,它会创建一个新的局部变量。

所以你想要做的是:

hp = None
lvl = None
atk = None
defn = None

def LON():
    global hp, lvl, atk, defn
    # rest of LON

# rest of the functions

但我应该警告你,全局变量是不好的编程习惯,传递参数是正确的方法。

于 2012-04-21T04:21:29.323 回答
0

您需要做的是将函数移动到 python 类中。这样类内的所有函数都可以访问变量,而无需将它们设为全局变量。

您可能会像这样构造代码:

#!/usr/bin/python

#import os
import time
print ("Hello and welcome to Pygame!")
time.sleep(1)
print ("Would you like to load? (\"Y/N\")")

class Game:

  def InitialiseNewPlayer(self):
    self.hp = 100
    self.lvl = 1
    self.atk = 5
    self.defn = 2

  def SavePlayer(self):
    fout = open("pygame.dat", "w")
    fout.write ( str(self.hp) ) 
    fout.write("\n")
    fout.write(str(self.lvl) )
    fout.write("\n")
    fout.write(str(self.atk) )
    fout.write("\n")
    fout.write(str(self.defn) )
    fout.close()

  def LoadPlayer(self):
     fin = open("pygame.dat", "r")
     self.hp = int(float(fin.readline()))
     self.lvl = int(float(fin.readline()))
     self.atk = int(float(fin.readline()))
     self.defn = int(float(fin.readline()))
     fin.close()

  def LON(self):
    while true:
      loadOrNew = raw_input()

      if loadOrNew == "N":
        self.InitialiseNewPlayer()
        self.SavePlayer();
        self.FIRSTPLAY()
        return

      if loadOrNew == "Y":
        self.LoadPlayer()
        return

      print("Im sorry, what?")

  # Watch out as this is using a different format to the SavePlayer above!
  def SAVE(self):
    fout = open("pygame.dat", "w")
    fout.write(self.hp)
    fout.write(self.lvl)
    fout.write(self.atk)
    fout.close(self.defn)


  def FIRSTPLAY(self):
    print("man/woman?")
    gender = raw_input()
    if gender != "man" and gender != "woman":
        print("Not valid gender.")
        FIRSTPLAY()

    print("KING - ")    
    print(" Young " + gender + ", you are herby my knight!")
    time.sleep(1)
    print(" My daughter, princess PYTHON, has been captured!")
    time.sleep(1)
    print(" You are to find her, and relieve this world of her captor!")
    time.sleep(1)
    print(" Some say this evil man's name is GAMEMAKER, but we really don't know.")
    time.sleep(1)
    print(" What do you think it is?")
    captor = raw_input()
    time.sleep(1)
    print(" So you think it is " + captor + "?")
    time.sleep(1)
    print("     Very well, find " + captor + " ASAP!")
    self.PLAY()
    return

  def PLAY(self):
      print self.hp
      print self.lvl
      print self.atk
      print self.defn
      self.greenSlime()

  def greenSlime(self):
    MHP = 10
    MLVL = 1
    MATK = 2
    MDEF = 2
    print "Green Slime - "
    print " HP: 10"
    print " LVL: 1"
    print " ATK: 2"
    print " DEF: 2"
    print "ATK OR DEF?"

game = Game()
game.LON()
于 2012-05-16T03:37:37.563 回答