[英]Same Variable in different Functions. (Python)
Newbie here, I am currently writing a "game" in ex 36 of LearnPythonTheHardWay. 新手在这里,我目前正在LearnPythonTheHardWay的ex 36中编写一个“游戏”。
If I wanted to ask for the user's name in one function. 如果我想在一个函数中询问用户名。 How can I recall that persons name in all the other functions without asking for it again, or setting it = to the name again? 我如何回想起人们在其他所有功能中的名字,而无需再次询问,或再次将其设置为=? From my understanding variables in a function don't affect other functions, but what if I want it to? 根据我的理解,一个函数中的变量不会影响其他函数,但是如果我希望它会怎样呢?
def room_1():
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
print "Hi %s" % name
Two ways, first would be to create a class and set an attribute called playername
. 有两种方法,第一种是创建一个类并设置一个名为playername
的属性。 Something like: 就像是:
class Game(object):
def __init__(self,playername=None):
if playername is None: self.playername = raw_input("What's your name? ")
else: self.playername = playername
# initialize any other variables here
def run(self):
# all your code goes here, and self.playername
# is always your player's name.
game = Game()
game.run()
The other was is widely (and properly!) frowned upon. 另一个被广泛使用(并且正确!)。 You could use a global 您可以使用全局
global name
name = raw_input("What is your name? ")
Now so long as you don't overwrite name
in any of your functions, they can call name
and access it as if it were a local variable. 现在,只要你不覆盖name
在你的任何功能,它们可以调用name
和访问它,仿佛它是一个局部变量。
EDIT: It looks like you're trying to build a game that should implement a Finite State Machine which is almost certainly beyond your ability to make right now. 编辑:看来您正在尝试构建一款应该实现有限状态机的游戏,这几乎肯定超出了您现在的能力。 You can CERTAINLY do it without one, but the code will always have that "spaghetti" feel to it. 您当然可以不用任何工具就能做到这一点,但是代码总会带有“意大利面条”的感觉。 class Game
is the first step towards the FSM, but there's a long way to go :) class Game
是迈向FSM的第一步,但是还有很长的路要走:)
You should declare it as global when asking for the name, so it is available in other functions: 询问名称时,应将其声明为global,因此在其他函数中也可以使用它:
def room_1():
global name
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
print "Hi %s" % name
For now you can define a variable outside of a function, then call it with the global
keyword. 现在,您可以在函数外部定义变量,然后使用global
关键字进行调用。
Normally you would use a class for this sort of thing, but you'll get there eventually :o) 通常,您将使用一个类来进行此类操作,但是最终您会到达那里:o)
name = ''
def room_1():
global name
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
global name
print "Hi %s" % name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.