python - 我可以在 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
感谢您阅读我的问题。
解决方案
在视图函数范围之外定义变量,并在函数内部使用 global 表示您要从内部使用变量。
variable = "value"
def viewfunction():
global variavle
print(variable)
推荐阅读
- c - 同一动态分配中的两种类型
- java - sqlContext.createDateFrame() 时的 NPE
- ios - 将数值数组的特定索引与 Swift 中的 Int 变量进行比较
- facebook-graph-api - Facebook - 无效范围:manage_pages , publish_pages 当我的应用程序处于实时模式时
- android - 从 Worker 创建位图
- r - 使用变量与硬编码值时得到不同的结果?
- angular - ng build prod 缺少延迟加载的子模块
- jquery - 如何使用 CSS3、HTML5、SVG 和 Jquery 创建不规则曲线?
- android - getColumnIndex 为 Android 的 Room 中的一列
- json - Angular *ngFor 数据匹配