首页 > 解决方案 > 如何在 Python 处理中将变量设置为 = 宽度或高度?

问题描述

我是 Python 新手,遇到以下问题。

通常情况下,如果你想在Jave Processing中定义一个窗口的高度、宽度或宽度/2的变量,可以如下声明:

int x = width/2;
int y = height/2;

但是,在 Python 中尝试这样做会引发错误:

NameError: name 'width' is not defined 

这是我使用 Python 编写的代码:

class Ball:
    x = width/2
    y = height/2

    def draw(self):
        ellipse(self.x, self.y, 20, 20)

提前致谢 :)

标签: pythonprocessing

解决方案


您编写的代码不是一个完整的class定义,您应该__init__()在初始化类变量时使用该函数来初始化类中的元素。

class Ball:
    def __init__(self, width, height):
        self.x = width/2
        self.y = height/2

    def draw(self):
        ellipse(self.x, self.y, 20, 20)

class_var = Ball(width,height)

创建一个类变量


推荐阅读