[英]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
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. 现在,我假设
point
变量是Point
类的实例。 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: 因此,您对
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
)
If you overwrite builtin __eq__
method (which is responsible for the behaviour of ==
operator) on Point
class like this: 如果您在
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
then same
method can be simplified to: 然后可以将
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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.