Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two instances are of the same class Python

Tags:

python

class

So in my pygame game, I have created a list of objects to make things like updating them all and collision checking easier. So when I'm collision checking, I have to check if the current object is the same as the object we are collision checking with. Here is my current code:

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

(All objects in the list/array are a child to the su)

like image 526
null Avatar asked Apr 24 '15 02:04

null


2 Answers

Simple, yet powerful => 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
>>>
like image 78
AmirHossein Avatar answered Sep 28 '22 09:09

AmirHossein


Apart from type way in previous answer, I think you can use isinstance. https://docs.python.org/2/library/functions.html#isinstance

Operator is can be used for object checking such as a is b if a and b are same objects. Remember is checks only objects and not their values. Or, I havenot seen anyone do this, I guess id(obj1) == id(obj) would work as well when you need to check if two objects are same.

like image 43
sagarchalise Avatar answered Sep 28 '22 10:09

sagarchalise