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

标签 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

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

最佳答案

简单而强大 => 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
>>>

关于python - 如何检查两个实例是否属于同一类 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29837656/

相关文章:

python - 从 Excel 工作表导出后如何清理数据框中的日期时间字符串?

python - 写入二进制文件时 Python 中缺少字节?

c++ - 如何在C++中将对象的类更改为其当前类的子类?

python - 如何更改 __init__ 中的类属性?

python - 如何用 pandas DataFrame 中之前和后续值的平均值替换 NaN?

python - 尝试在不使用 Anaconda 的情况下通过 cmd 安装seaborn 时出错

c++ - QT中如何从文件中读取数据并显示在QEditText框中

java - 输入 2 个变量(用户输入 "Buffered Reader")传递给一个类?

PHP - 使用常量的值来引用数据成员

c++ - 如果 "struct"和 "class"是同一件事,那么为什么在 template<class T> 中只使用 "class"而不是 "struct"?