 B.Verbeke - 3 years ago 139
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):
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
`````` freakish

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
)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download