这是我的第一个类
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)
更好的方法可能是定义一个适用于任何两个对象的函数。这样,您可以将功能扩展到具有属性 x
、y
、height
、width
的任何类。
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/