B.Verbeke B.Verbeke - 8 months ago 51
Python Question

Python: how can I differentiate between two variables of two different objects of the same class?

I have a problem with a task for school. I want my last method to test if two rectangles are the same. The only problem there is that I can't seem to differentiate between the two different heights, widiths and the different point(this is the left-low corner point of the rectangle) of the two different rectangles, any advice?

Thanks a lot

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

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

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


First of all don't use the same name for function params and classes. It makes the code confusing and error prone. Try this:

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

Now I assume that point variable is an instance of Point class. In that case comparing one point to another via == will fail, because by default == checks if two objects are the same in the sense of being the same object in memory.

Thus your implemenatation of same method may look like this:

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

If you overwrite builtin __eq__ method (which is responsible for the behaviour of == operator) on Point class like this:

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

then same method can be simplified to:

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