【问题标题】:Import Variable from function in Class从类中的函数导入变量
【发布时间】:2017-11-07 03:15:32
【问题描述】:

我不知道如何导入在函数和类的循环中创建的变量。然后我会遇到错误“ AttributeError: "Example" object has no attribute "address" 。

看起来像这样:

a.py

class Example():
    global address
    address = ""

    def __init__(self):
        pass

    def loop_function(self, cam):

        for i in imageZbar.symbols:
            print(i.data)
            address = i.data
        return address

b.py

from a import Example
from flask import Flask,render_template
app = Flask(__name__)

app.route("/example/")
def blabla():
    imported_address = Example.address
    return render_template("example.html", imported_address = imported_address)

【问题讨论】:

  • b.py,你可以做imported_address = Example().loop_function()。这还不够吗?你不需要做任何事情global
  • 抱歉,loop_function() 实际上有 2 个参数,我刚刚编辑了它。当我确实喜欢你所描述的时,它会说“正好需要 2 个参数(给定 1 个)。”
  • 然后将第二个参数传递给loop_function()。第一个参数是self,默认传递。
  • 如果我在 b.py 中使用 Example().loop_function(cam) 我有一个 NameError 'global name 'cam' is not defined'
  • 你想达到什么目的?在我看来,您根本不需要 Example 课程

标签: python class oop flask import


【解决方案1】:

只需删除global address这一行

【讨论】:

    【解决方案2】:

    不知道为什么你放一个全局的当它表现得像一个类成员时......为什么不使用:

    a.py

    class Example():
    
        def __init__(self):
            self.address = ""
    
        def loop_function(self, cam):
            for i in imageZbar.symbols:
                print(i.data)
                self.address = i.data
            return self.address
    

    b.py

    from a import Example
    
    app = Flask(__name__)
    eg = Example()
    cam = None # I do not see anywhere this variable
    eg.loop(cam)
    
    app.route("/example/")
    def blabla():
        return render_template("example.html", imported_address = eg.address)
    

    如果你不需要它表现得像一个类(即只想使用循环函数),为什么还要费心创建一个类,你为什么不创建一个函数。另外,为什么它必须是全球性的?

    顺便说一句,检查 cmets,你有一个变量 cam 的错误......我没有看到你在代码中的任何地方初始化它

    另外,你没有显示你从哪里得到:

     imageZbar.symbols
    

    据我所知,这应该是循环函数的参数

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2017-10-15
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 2019-12-11
      • 2021-07-13
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多