繁体   English   中英

我可以在 Flask 中将 object 声明为全局变量吗?

[英]Can I declare an object as a global variable in Flask?

我是一名学习编程的学生。 我正在制作一个网站,用户可以在其中练习数字和字母并解决测验。 (使用烧瓶)

我可以将 object 声明为全局变量,例如 num=Number() 和 alpha=Alphabet(),并在多个视图函数中使用它吗?

在 Java 中,我可以使用 bean 创建对象,但我不知道如何使用 python 来创建对象。

或者有什么方法可以在不使用 Class 和 Inheritance 的情况下解决这个问题?

class Group:
def __init__(self):
    self.label=[]
    self.g_list=[]

def get_label(self,idx):
    return self.label[idx]
def get_list(self):
    return self.g_list
def list_next_prev_idx(element):
    next_topic = ""
    previous_topic = ""

    group_list = get_list()

    list_idx_end = len(group_list) - 1  
    idx_now = group_list.index(element)

    if idx_now == list_idx_end:
        next_topic = group_list[0]
    else:
        next_topic = group_list[idx_now + 1]

    if idx_now != 0:
        previous_topic = group_list[idx_now - 1]

    return next_topic, previous_topic

class Number(Group):
        def __init__(self):
            self.label=["0","1","2","3","4","5","6","7","8","9",
             "del", "nothing", "space"]
            self.g_list=['0','1','2','3','4','5','6','7','8','9']


class Alphabet(Group):
        def __init__(self):
            self.label=["A", "B", "C", "D", "E", "F", "G",
             "H", "I", "K", "L", "M", "N", "O", "P", "Q",
            "R", "S", "T", "U", "V", "W", "X", "Y",
            "del", "nothing", "space"]
            self.g_list=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o',
                      'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']


num=Number()
alpha=Alphabet()

@app.route('/practice/<group>')
def practice(group):
    if group =="alphabet":
        practice_list=alpha.get_list()
    elif group =="number":
        practice_list=num.get_list()


    #omit

感谢您阅读我的问题。

在视图 function 的 scope 外部定义变量,并在函数内部使用 global 表示您要从内部使用该变量。

variable = "value"

def viewfunction():
    global variavle
    print(variable)

暂无
暂无

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

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