Python 类的全面介绍
1. 类的基础示例:Ball 类
在 Python 和 Pygame 中,我们可以使用类来管理数据,使代码更加清晰和易于维护。以 Ball 类为例,以下是其代码实现:
class Ball():
def __init__(self):
# --- 类属性 ---
# 球的位置
self.x = 0
self.y = 0
# 球的向量
self.change_x = 0
self.change_y = 0
# 球的大小
self.size = 10
# 球的颜色
self.color = [255, 255, 255]
# --- 类方法 ---
def move(self):
self.x += self.change_x
self.y += self.change_y
def draw(self, screen):
pygame.draw.circle(screen, self.color, [self.x, self.y], self.size)
在主程序循环之前,我们可以创建一个球的实例并设置其属性:
theBall = Ball()
theBall.x = 100
theBall.y = 100
theBall.change_x