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

2024-04-19 04:12:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

或者有没有办法不使用Class&;解决这个问题;继承权

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

谢谢你阅读我的问题


Tags: selfalphanumbergettopicdefgroupnow
1条回答
网友
1楼 · 发布于 2024-04-19 04:12:46

在view函数的作用域之外定义变量,并在函数内部使用global以指示要从内部使用变量

variable = "value"

def viewfunction():
    global variavle
    print(variable)

相关问题 更多 >