未定义全局变量 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28237966/
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 variable is not defined - Python
提问by Milano
I have a problem with global variable. It returns error
我有全局变量的问题。它返回错误
search = Search.Search(pattern,b)
NameError: global name 'b' is not defined
But I have already defined this global variable. I tried to put it even into the search function. I think that there was no problem with that on Windows. I'm trying to run this program on Linux/Unix.
但是我已经定义了这个全局变量。我什至试图将它放入搜索功能中。我认为在 Windows 上没有问题。我正在尝试在 Linux/Unix 上运行这个程序。
Do you have any advice how to avoid this error?
您对如何避免此错误有什么建议吗?
# -*- coding: utf-8 -*-
from flask import Flask
from flask import request
from flask import render_template
import Search
import B
app = Flask(__name__)
global b
@app.route('/')
def my_form():
return render_template('my-form.html')
def setup():
global b
b = B.B()
@app.route('/', methods=['POST'])
def search():
global b
from time import time
pattern = request.form['text']
...
se = Search.Search(pattern,b)
...
...
...
app.debug=True
if __name__ == '__main__':
setup()
app.run()
采纳答案by Kevin
app = Flask(__name__)
global b
The global b
statement here does not actually create a variable for you. You need to assign something to it yourself.
global b
此处的语句实际上并未为您创建变量。你需要自己给它分配一些东西。
app = Flask(__name__)
b = None #or whatever you want the starting value to be