首页 > 解决方案 > 以 Python 方式使 geopy.Point 更具可读性

问题描述

我目前正在使用 Python 3.5 下的 geopy 包。我使用 geopy.Point 包。我将它包含在很多文件中,从未遇到过问题。不幸的是,我现在在调试时遇到了麻烦,因为 Point__str__函数默认使用大地基准系统作为输出。

如果可能的话,我宁愿只看到纬度和经度。我不知道 geopy 为什么使用这个大地测量系统,所以可能是我没有得到它的优势。但据我所知,这个系统对调试没有多大帮助。所以现在我寻求一种以__str__非常优雅的方式改变功能的方法。最pythonic的方法是什么?据我所知,仅编写一个包装器就会使代码完成变得混乱。

这里有一个例子来解释我的意思:

from geopy.point import * #import the package

def str_p(point): #a function to get the format I actually can read
    return "Lat= "+str(point.latitude)+" | "+"Long= "+str(point.longitude) #always writing .latitude or .longitude when debugging is troublesome

p = Point(55, 17) #create a Point, note that we are using Lat, Lng
print(p) # 55 0m 0s N, 17 0m 0s E , a good format if you are manning a pirate ship. But confusing to me
print(str_p(p))# what I want

标签: pythonpython-3.xgeopy

解决方案


这很hacky,这可能不是最好的解决方案,但出于调试目的,您总是可以猴子补丁:

In [1]: from geopy.point import Point

In [2]: old_str = Point.__str__

In [3]: Point.__str__ = lambda self:  "Lat= {} | Long= {}".format(self.latitude, self.longitude)

In [4]: p = Point(55, 17)

In [5]: print(p)
Lat= 55.0 | Long= 17.0

In [6]: Point.__str__ = old_str

In [7]: print(p)
55 0m 0s N, 17 0m 0s E

推荐阅读