Python中的全局静态变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3694580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global static variables in Python
提问by Denis
def Input():
c = raw_input ('Enter data1,data2: ')
data = c.split(',')
return data
I need to use list datain other functions, but I don't want to enter raw_inputeverytime. How I can make datalike a global staticin c++ and put it everywhere where it needed?
我需要data在其他功能中使用列表,但我不想raw_input每次都输入。我如何在 C++ 中创建data一个全局静态并将其放在需要的任何地方?
采纳答案by Greg Hewgill
Add a single line to your function:
在您的函数中添加一行:
def Input():
global data
c = raw_input ('Enter data1,data2: ')
data = c.split(',')
return data
The global datastatement is a declaration that makes dataa global variable. After calling Input()you will be able to refer to datain other functions.
该global data语句是创建data全局变量的声明。调用Input()后就可以data在其他函数中引用了。
回答by Ivo van der Wijk
using global variables is usually considered bad practice. It's better to use proper object orientation and wrap 'data' in a proper class / object, e.g.
使用全局变量通常被认为是不好的做法。最好使用适当的面向对象并将“数据”包装在适当的类/对象中,例如
class Questionaire(object):
def __init__(self):
self.data = ''
def input(self):
c = raw_input('Enter data1, data2:')
self.data = c.split(',')
def results(self):
print "You entered", self.data
q = Questionaire()
q.input()
q.results()

