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

问题描述 投票:0回答:2

这里是我的第一堂课

 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”不是一个错误定义。谢谢。

python pygame
2个回答
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, s):
        """ Return whether this food particle collides with the object `s`.
        # TODO:  use `s.x` and `s.y` and check whether they are 
        # close to `self.x` and `self.y`.

更好的方法可能是定义一个对任何两个对象都有效的函数:

def is_collision(obj1, obj2):
    """ Return whether obj1 and obj2 collide. """
    # TODO:  use 

0
投票

您必须实例化该类。然后,您可以使用其方法和功能,但不能使用其变量。在类中创建一个返回所需内容的函数,从另一个(或主程序)中实例化该类并获取返回的值。

下面是一个例子:

class A:
    def m(self, x, y):
        return x + y

class B:
    def __init__(self):
        self.a = A()

    def call_a(self):
        a = self.a.m(1, 2)
        return a

c = B()
result = c.call_a()
print(result)
© www.soinside.com 2019 - 2024. All rights reserved.