作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
好的!基本上,我在一个函数中声明了一个变量,并且我想在另一个函数中使用该变量。我不想传递参数,因为我觉得会有一种更简单的方法来做到这一点。这是我的代码:
#!/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 变量。我确信有一种比传递参数更简单的方法。
最佳答案
仅在全局中声明变量是行不通的。 global 关键字是要求解释器在给某个东西赋值时不要将其视为局部变量(覆盖同名的全局变量)。您需要做的是将变量定义在应该共享它的函数之上的范围内。请注意,您不需要在函数中声明全局变量以进行只读访问。当解释器在本地作用域中找不到该变量时,它会自动在外部作用域中查找它。但在赋值语句的情况下,它会创建一个新的局部变量。
所以你想做的是:
hp = None
lvl = None
atk = None
defn = None
def LON():
global hp, lvl, atk, defn
# rest of LON
# rest of the functions
但我应该警告您,全局变量是不好的编程习惯,传递参数是正确的方法。
关于python - 这可能是一个新事物......但是,全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10255991/
我是一名优秀的程序员,十分优秀!