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

问题描述 投票:0回答:1

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

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

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

或者是否有任何方法可以在不使用类和继承的情况下解决此问题?

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

感谢您阅读我的问题。

python oop flask global-variables
1个回答
0
投票

在视图函数的范围之外定义变量,并在函数内部使用global表示要从内部使用变量。

variable = "value"

def viewfunction():
    global variavle
    print(variable)
© www.soinside.com 2019 - 2024. All rights reserved.