【问题标题】:Make geopy.Point more readable in an pythonic way以 Python 方式使 geopy.Point 更具可读性
【发布时间】:2019-02-03 20:45:39
【问题描述】:

我目前正在使用 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

【问题讨论】:

  • geopy 维护者在这里。您不必是海盗就可以真正需要地理位置格式。我相信你正在搜索的是repr(Point(55, 17)),它会给你'Point(55.0, 17.0, 0.0)'

标签: python python-3.x geopy


【解决方案1】:

这很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

【讨论】:

  • 可行,但我真的想要一个更优雅的解决方案。最好是我不必每次包含包裹时都重做。
  • @not_a_bot_no_really_82353 “每次我包含一个包”是什么意思?
  • 我说过每次我都包含包,就像每次使用 geopy.point 时一样,因此在文件中包含 geopy.point。这是很多。我确实想使用这个包,但不想跳槽。所以我目前写了一个包装器来包装所有东西。很糟糕,但它困扰我
  • @not_a_bot_no_really_82353 您不必每次都这样做,每个进程只需执行一次。与使用包装器有何不同?
  • 我在至少 16 个不同的文件和 3 个项目中包含 geopy.point 点。所以我希望有一个能够真正改变 geopy.point 包本身的解决方案。现在我构建自己的包并更改导入。我认为这是侵入性最小的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 2021-11-14
相关资源
最近更新 更多