添加适用于点对象或元组的方法
我的一个练习是为 Points 编写一个与 Point 对象或元组一起使用的 add 方法:
- 如果第二个操作数是 Point,该方法应该返回一个新的 Point,其 x 坐标是操作数的 x 坐标之和,y 坐标也是如此。
- 如果第二个操作数是元组,则该方法应将元组的第一个元素添加到 x 坐标,将第二个元素添加到 y 坐标,并返回一个新的 Point 和结果。
这就是我已经走了多远,我不确定我的代码的元组部分是否准确。有人可以阐明我如何为元组部分调用这个程序吗?我想我已经完成了第一部分。
这是我的代码:
Class Point():
def__add__(self,other):
if isinstance(other,Point):
return self.add_point(other)
else:
return self.print_point(other)
def add_point(self,other):
totalx = self.x + other.x
totaly = self.y + other.y
total = ('%d, %d') % (totalx, totaly)
return total
def print_point(self):
print ('%d, %d) % (self.x, self.y)
blank = Point()
blank.x = 3
blank.y = 5
blank1 = Point()
blank1.x = 5
blank1.y = 6
这是我到目前为止构建的代码,我不确定如何使用元组部分实际运行它。我知道如果它执行了 blank + Blank1
if 部分将运行并调用 add_point
函数,但我如何启动元组。我不确定我写得是否正确......请帮忙。
One of my exercises says to write an add method for Points that works with either a Point object or a tuple:
- If the second operand is a Point, the method should return a new Point whose x coordinate is the sum of the x coordinates of the operands, and likewise for the y coordinates.
- If the second operand is a tuple, the method should add the first element of the tuple to the x coordinate and the second element to the y coordinate, and return a new Point with the result.
This how far I got and I'm not sure if the tuple portion of my code is accurate. Can someone shed some light how I would call this program for the tuple portion. I think I nailed the first part.
Here is my code:
Class Point():
def__add__(self,other):
if isinstance(other,Point):
return self.add_point(other)
else:
return self.print_point(other)
def add_point(self,other):
totalx = self.x + other.x
totaly = self.y + other.y
total = ('%d, %d') % (totalx, totaly)
return total
def print_point(self):
print ('%d, %d) % (self.x, self.y)
blank = Point()
blank.x = 3
blank.y = 5
blank1 = Point()
blank1.x = 5
blank1.y = 6
That's what I've built so far and I'm not sure how to actually run this with the tuple part. I know if it did blank + blank1
the if portion would run and call the add_point
function but how do I initiate the tuple. I'm not sure if I wrote this correctly... please assist.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以简单地从元组派生您的类(或者仅实现
__getitem__
)。You can simply derive your class from the tuple (or just implement
__getitem__
).或者,如果您希望能够使用 point.x 和 point.y 语法,您可以实现以下内容:
Alternatively, if you want to be able to use point.x and point.y syntax, you could implement the following: