【问题标题】:Processing variables unassigned处理未分配的变量
【发布时间】:2018-04-20 04:23:11
【问题描述】:
x = 0
y = 0
tx = 0
ty = 0

def setup():
    size(600, 600)
    noStroke()

def draw():
    background(0)
    textAlign(LEFT,TOP)
    # text("Hello World",x,y)
    tx=mouseX
    ty=mouseY
    f=0.01
    #The error: "UnboundLocalError: local variable 'x' referenced before assignment"
    x=lerp(x,tx,f)
    y=lerp(y,ty,f)

这是处理python代码。 我在 Mac OSX High Sierra 10.13.1 上,使用处理 3.3.6 和 Python 模式 3037。

此代码在代码中注释行之后的行中给出“UnboundLocalError: local variable 'x' referenced before assignment”。

我是 python 新手,这似乎是谷歌所说的。

编辑: 另外,如何在类方法中引用全局变量和实例变量?

【问题讨论】:

    标签: python python-3.x oop variables processing


    【解决方案1】:

    要在函数中修改全局变量,您需要使用global 语句,如下所示:

    def draw():
        global x, y, tx, ty
        background(0)
        ...
    

    如果您使用的是类,您的代码将如下所示:

    class Drawer(object):
        def __init__(self):
            self.x = 0
            self.y = 0
            self.tx = 0
            self.ty = 0
    
        def setup(self):
            size(600, 600)
            noStroke()
    
        def draw(self):
            background(0)
            textAlign(LEFT, TOP)
            # text("Hello World",x,y)
            self.tx = mouseX
            self.ty = mouseY
            f = 0.01
            self.x = lerp(self.x, self.tx, f)
            self.y = lerp(self.y, self.ty, f)
    
    d = Drawer()
    d.setup()
    d.draw()
    

    【讨论】:

    • 这似乎有点承认总是不得不使用全局语句。那么这对课程有什么作用呢?
    • @mackycheese21 你可以use singleton
    【解决方案2】:

    应该工作吗?我不喜欢python,这是别人写的

    x = 0
    y = 0
    tx = 0
    ty = 0
    
    def setup():
        size(600, 600)
        noStroke()
    
    def draw():
        global x, y, tx, ty
        background(0)
        textAlign(LEFT,TOP)
        # text("Hello World",x,y)
        tx=mouseX
        ty=mouseY
        f=0.01
        x=lerp(x,tx,f)
        y=lerp(y,ty,f)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多