如何以pythonic方式实现不同类型之间的距离

2024-04-18 19:09:59 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有不同的类型,比如:

Point 
Circle 
Rectangle
Polyline
Circle_Collection
Rectangle_collection

等等

我想能够测量上述任何类型的组合之间的距离。最简单的方法是在每个类中实现距离方法:

class Point:
   def distance(self, other):
      if other is Point:
         # handle points
      if other is Circle:
         # handle circles

但后来我认为最好将它实现为一个自由函数,因为到另一个对象的距离并不是一个类的固有信息。你知道吗

假设我用一种我可以称之为

p = Point()
c = Cirle()
print distance(p,c)

最好的方法是什么?我听说函数重载并不是一种真正可行的方法。什么是正确的?你知道吗


Tags: 方法函数距离类型ifiscollectiondistance
1条回答
网友
1楼 · 发布于 2024-04-18 19:09:59

如果你想测量每个形状中点之间的距离,这个问题就容易多了。在一些公共祖先Shape上实现:

@property
def midpoint(self):
    """returns the midpoint of the shape as
    the tuple (x,y)"""
    # however you'll do this based on your structure
    #
    # note that if your shapes are immutable, you should make this
    # a regular attribute, not a property. I'm assuming your shapes
    # can move

@staticmethod
def distance(a, b):
    a_x, a_y = a.midpoint
    b_x, b_y = b.midpoint
    return (abs(a_x - b_x), abs(a_y - b_y))

你说得对,求两点之间的距离在某种程度上脱离了物体本身(即一个物体不应该知道如何求出它到另一个物体的距离),但它确实符合一个形状应该知道的东西。你知道吗

通过调用运行

foo = Circle()
bar = Rectangle()

dist = Shape.distance(foo, bar)

相关问题 更多 >