我是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)
先谢谢你:)
要使用任何一个变量,你都应该给它赋值,这是所有编程语言的规则。这是所有编程语言的规则。所以,你没有给以下变量赋值 width
和 height
变量width,height应该定义在类成员变量中或者全局变量中,例如,可以在构建类的时候设置,像这样。
class Ball:
def __init__(self, width, height):
self.width = width
self.height = height
self.x = self.width/2
self.y = self.height/2
def draw(self):
ellipse(self.x, self.y, self.width, self.height)
你写的代码不是一个完整的 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)
来创建一个类变量
我想指出的是,这个问题与Processing有关,其中 width
和 height
应该是由框架在全局范围内预定义的,所以像 "要使用任何变量,你都应该给它赋值 "这样的回答并没有什么用。
我不太懂用python进行处理,但可能需要用到 输入 width
和 height
变量在文件的顶部。
from processing import width, height
另外,我的建议是在你的项目的主文件中
class Ball:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
ellipse(self.x, self.y, 20, 20)
和在项目的主文件中
b = Ball(width/2, height/2)
因为这样更简洁。