python - 如何在 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)
提前致谢 :)
解决方案
您编写的代码不是一个完整的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)
创建一个类变量
推荐阅读
- python - 数字选择器程序随机返回“无”
- linux - 如何将一个元素附加到 GNU bash 数组变量并将该数组变量用作 ELF 可执行文件的参数
- c# - 如何在 C# 中使用 FromRoute 属性围绕属性编写单元测试
- android-studio - Android Studio 显示错误并报告给 google
- wordpress - 使用带有参数“showposts”= 1 的 WP_query,但结果显示为 2 - Wordpress
- c# - 将数据输入到WPF C#中的上一行控件后,如何动态添加控件行?
- c++ - 当您创建的棋盘中有一个超过 1 位的数字时,您应该怎么做才能防止它影响棋盘的形状
- json - 如何使用 gitlab-ci.yml 在 gitlab 中更新 JSON 文件的内容?
- three.js - 如何制作具有多种领型的 3d 模型衬衫?
- java - 如何通过 Windows 上内置的 tomcat 脚本文件启动和停止 tomcat?