python - 从 Python 类外部的函数引用定义的变量

标签 python django

请原谅新手问题,但我想自己弄清楚。我在类外的函数内访问类变量时遇到问题。在下面的代码中,我需要 text, text2。我将变量作为元组获取,但我需要单独使用它们。如何更新代码以获取定义的变量,如 text = var1text2 = var2?提前致谢!

from django.shortcuts import render

class Someclass():
    def method_1(self):
        self.var2 = 'var2'
        self.var1 = 'var1'
        return self.var1 ,self.var2

def func(request):
    cls = Someclass()
    text2 = cls.method_1()
    text = cls.method_1()
    content = {
        'text': text,
        'text2': text2,
    }
    return render(request, "web/page.html", content)

最佳答案

由于您返回的是元组,因此您应该在一次调用中直接将它们的值分配给变量。

像这样:

text, text2 = cls.method_1()

关于python - 从 Python 类外部的函数引用定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825630/

相关文章:

javascript - AJAX 请求永远不会发送。为什么?

python - 在虚拟环境中手动安装包并且 pip 要求知道

python - Tkinter——如何水平居中 Canvas 文本?

Python - 使用 map(sys.stdin.readline()) 存储一个字符串和一个 int

python - Ubuntu 为 Django 设置环境变量

Django 脆皮形式与 jinja2

(node_id, parent_node_id) 到 JSON 的 Python 列表

python - 理解Python中的递归和堆栈

python - Plotly:躲避散点图分类轴上的重叠点

python - Django休息框架: Generate a unique obfuscated ID from ID field