未定义全局变量-Python [英] Global variable is not defined - Python

查看:84
本文介绍了未定义全局变量-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对全局变量有疑问。返回错误

I have a problem with global variable. It returns error

search = Search.Search(pattern,b)
NameError: global name 'b' is not defined   

但是我已经定义了这个全局变量。我试图将其甚至放入搜索功能。我认为Windows上没有问题。我正在尝试在Linux / Unix上运行该程序。

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.

您对如何避免此错误有任何建议吗?

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

此处的全局b 语句实际上并未为您创建变量。您需要自己分配一些东西。

The global b statement here does not actually create a variable for you. You need to assign something to it yourself.

app = Flask(__name__)

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

这篇关于未定义全局变量-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆