我需要添加一个 eq 方法,如果坐标引用平面中的同一点(即,具有相同的x和y坐标),并且返回结果感到困惑,则该方法返回True。
我使用 eq 尝试了一些代码,但仍然出现错误,我不确定为什么。
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def getX(self):
# Getter method for a Coordinate object's x coordinate.
# Getter methods are better practice than just
# accessing an attribute directly
return self.x
def getY(self):
# Getter method for a Coordinate object's y coordinate
return self.y
def __str__(self):
return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
def __eq__(Coordinate, otherPoint):
if self.GetX() == otherPoint.getX()&& self.GetY() == otherPoint.getY()
return True
x=5
y=5
如果两个坐标都是相同的数字,则预期输出将返回true;如果x和y不是相同的数字,则预期输出将返回false。
答案 0 :(得分:3)
您的代码中的某些问题/解决方法
GetX
和GetY
,可以直接引用属性x
和y
。 &&
在Python中不是有效的语法,而是使用and
__eq__
的第一个参数为self
f-strings
格式化字符串,否则可以使用格式化字符串TypeError
以确保other
的类型为Coordinate
因此更新后的代码如下
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
#Use a f-string to format your string representation
return f'<{self.x},{self.x}>'
#If python3.5 and below, you can use format string as below
#return '<{},{}>'.format(self.x, self.y)
def __eq__(self, other):
#If other is not an instance of Coordinate, raise TypeError
if not isinstance(other, Coordinate):
raise TypeError('An instance of class Coordinate is expected')
#Compare both coordinates and return True or False
return self.x == other.x and self.y == other.y
然后您可以使用如下所示的类
c1 = Coordinate(5,5)
c2 = Coordinate(6,6)
print(c1)
#<5,5>
print(c2)
#<6,6>
print(c1 == c1)
#True
print(c1 == c2)
#False
print(c1 == 1)
#TypeError: An instance of class Coordinate is expected
答案 1 :(得分:3)
>>> class Coordinate:
... def __init__(self, x, y):
... self.x = x
... self.y = y
... def __eq__(self, other):
... if not isinstance(other, Coordinate):
... raise TypeError('You can compare a Coordinate with only another Coordinate')
... return self.x == other.x and self.y == other.y
...
>>> Coordinate(1,2) == Coordinate(1,2)
True
>>> Coordinate(1,2) == Coordinate(1,3)
False
>>> Coordinate(1,2) == 'Hello'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in __eq__
TypeError: You can compare a Coordinate with only another Coordinate
>>>
答案 2 :(得分:2)
这么多小错误...
GetX
与getX
if
语句的末尾需要:
__init__
子句的缩进是错误的&&
在python中不存在,称为and
__eq__
函数并不总是返回,它需要一个else
子句,或者只是直接返回布尔表达式__eq__
的第一个参数必须为self
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def getX(self):
# Getter method for a Coordinate object's x coordinate.
# Getter methods are better practice than just
# accessing an attribute directly
return self.x
def getY(self):
# Getter method for a Coordinate object's y coordinate
return self.y
def __str__(self):
return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
def __eq__(self, otherPoint):
return self.getX() == otherPoint.getX() and self.getY() == otherPoint.getY()