简体   繁体   English

未定义全局变量-Python

[英]Global variable is not defined - Python

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. 我认为Windows上没有问题。 I'm trying to run this program on Linux/Unix. 我正在尝试在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()
app = Flask(__name__)

global b

The global b statement here does not actually create a variable for you. 此处的global b语句实际上并未为您创建变量。 You need to assign something to it yourself. 您需要自己分配一些东西。

app = Flask(__name__)

b = None #or whatever you want the starting value to be

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM