Python:如何区分同一类的两个不同对象的两个变量?

2024-10-02 08:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对学校的任务有意见。我想用我的最后一个方法测试两个矩形是否相同。唯一的问题是,我似乎无法区分两个不同的高度,宽度和两个不同矩形的不同点(这是矩形的左下角点),有什么建议吗?你知道吗

多谢了

class Point():
    def __init__(self,x,y):
        self.x=x
        self.y=y

class Rectangle():
    def __init__(self,Point,w,h):
        self.Point=Point
        self.widith=w**strong text**
        self.height=h

    def same(self,Rectangle):
        if Rectangle.self.Point==self.Point and Rectangle.self.widith==self.widith and Rectangle.self.height==self.height:
            return True
        else:
            return False

Tags: and方法selfreturninitdef学校class
1条回答
网友
1楼 · 发布于 2024-10-02 08:26:52

首先不要对函数参数和类使用相同的名称。这使得代码容易混淆和出错。试试这个:

class Rectangle:
    def __init__(self, point, width, height):
        self.point = point
        self.widith = width
        self.height = height

现在我假设point变量是Point类的实例。在这种情况下,通过==将一个点与另一个点进行比较将失败,因为默认情况下==检查两个对象在内存中是否是相同的对象。你知道吗

因此same方法的实现可能如下所示:

def same(self, other):
    return (
        self.point.x == other.point.x
        and self.point.y == other.point.y
        and self.width == other.width
        and self.height == other.height
    )

如果在Point类上覆盖内置的__eq__方法(它负责==运算符的行为),如下所示:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

那么same方法可以简化为:

def same(self, other):
    return (
        self.point == other.point  # now __eq__ will be called here
        and self.width == other.width
        and self.height == other.height
    )

相关问题 更多 >

    热门问题