我需要添加一个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。
发布于 2019-05-27 00:21:08
代码中的一些问题/修复
如果您实际上不需要GetX
和GetY
,则可以引用属性x
和y
__eq__
在Python中无效语法,而是使用and
__eq__
将是f-strings
如果您使用的是python3.6+,则可以使用
格式化字符串,否则可以使用格式化字符串<__eq__
>H118f-strings>您可以选择抛出<代码>D19,以确保D20为
因此,更新后的代码将如下所示
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
发布于 2019-05-27 00:21:23
>>> 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
>>>
发布于 2019-05-27 00:24:41
太多小错误了。
GetX
与getX
if
语句在末尾需要一个缩进,GetX
子句的缩进在python中不存在,它被称为and
getX
if
子句,或者只是直接返回布尔表达式< :
>d21>的第一个参数需要为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()
https://stackoverflow.com/questions/56315279
复制相似问题