如何检查两个实例是否属于同一类Python

nul*_*ull 3 python class

因此,在我的pygame游戏中,我创建了一个对象列表,以便更新所有对象并更轻松地进行碰撞检查.所以当我进行碰撞检查时,我必须检查当前对象是否与我们碰撞检查的对象相同.这是我目前的代码:

def placeMeeting(self, object1, object2):

    # Define positioning variables
    object1Rect = pygame.Rect(object1.x, object1.y, object1.width, object1.height)

    # Weather or not they collided
    coll = False

    # Loop through all walls to check for possible collision
    for i in range(len(self.instances)):

        # First check if it's the right object
        if (self.instances[i] == object2):
            print "yep"
            object2Rect = pygame.Rect(self.instances[i].x, self.instances[i].y, self.instances[i].width, self.instances[i].height)

            # Check for collision with current wall -- Horizontal
            if (object1Rect.colliderect(object2Rect)):
                coll = True

    # Return the final collision result
    return coll
Run Code Online (Sandbox Code Playgroud)

(列表/数组中的所有对象都是su的子对象)

Ami*_*ein 6

简单但强大=> type(a) is type(b)

>>> class A:
...     pass
...
>>> a = A()
>>> b = A()
>>> a is b
False
>>> a == b
False
>>> type(a)
<class '__main__.A'>
>>> type(b)
<class '__main__.A'>
>>> type(a) is type(b)
True
>>> type(a) == type(b)
True
>>>
Run Code Online (Sandbox Code Playgroud)


sag*_*ise 5

除了type之前的答案,我认为你可以使用isinstance. https://docs.python.org/2/library/functions.html#isinstance

运算符is可用于对象检查,例如a is ba 和 b 是否是相同的对象。记住is只检查对象而不是它们的值。或者,我还没有看到任何人这样做,我想当id(obj1) == id(obj)您需要检查两个对象是否相同时也会起作用。