python - 如何从一个类访问变量并在另一个类中使用它?

标签 python pygame

这是我的第一个类

 class snake:  
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.change_x = 0
        self.change_y = 0

这是我的第二堂课

 class food:
    def __init__(self, food_x, food_y, food_width, food_height):
        self.x = food_x
        self.y = food_y
        self.width = food_width
        self.height = food_height
    def collition_detection(self):
        pass

我希望能够从蛇类访问食物类的位置 (x, y),这样当我在食物类中创建“collition_detection”函数时,它不会向我抛出错误,说“self.x”是没有定义的。谢谢。

最佳答案

你可以在方法中带一个参数:

 class food:
    def __init__(self, food_x, food_y, food_width, food_height):
        self.x = food_x
        self.y = food_y
        self.width = food_width
        self.height = food_height

    def collition_detection(self, s):
        """ Return whether this food particle collides with the object `s`. """
        delta_x = math.abs(self.x - s.x)
        delta_y = math.abs(self.y - s.y)
        return (delta_x < (self.width + s.width) / 2) and (delta_y < (self.height + s.height) / 2)

更好的方法可能是定义一个适用于任何两个对象的函数。这样,您可以将功能扩展到具有属性 xyheightwidth 的任何类。

def is_collision(obj1, obj2):
    """ Return whether obj1 and obj2 collide. """
    delta_x = math.abs(obj1.x - obj2.x)
    delta_y = math.abs(obj1.y - obj2.y)
    return (delta_x < (obj1.width + obj2.width) / 2) and (delta_y < (obj1.height + obj2.height) / 2)

你可以这样调用它:

s = Snake(...)
f_particle = food(...)

is_collision(s, f_particle)

关于python - 如何从一个类访问变量并在另一个类中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59183556/

相关文章:

python - 使用 Dask 处理大型、压缩的 csv 文件

python - 减少和计数的结果在 pyspark 中不同

python - 根据pygame中的点击更改图像

python - 为什么此代码不生成具有随机颜色的形状?

python - 文本中术语的二阶共现

python - 如何更快地从列表中删除包含某些单词的字符串

python - 在 pandas boolean 比较中保留 NaN 值

python - 无法打开资源文件,pygame错误: "FileNotFoundError: No such file or directory."

python - 如何在我的 pygame 程序中实现此功能?

python - 我要在这段代码中添加什么才能使 'mylives' 下降(pygame)