【问题标题】:Getting a parameter from class object with no '__getitem__' attribute?从没有'__getitem__'属性的类对象中获取参数?
【发布时间】:2013-03-08 00:52:28
【问题描述】:

我正在使用pyproj.Geod 计算地理距离,我想使用对象定义的地球直径进行另一次计算。

当没有__getitem__属性并且对象不可索引时,有没有办法从中提取值?

调用对象:

import pyproj
g = pyproj.Geod(ellps='WGS84') # Use WGS84 ellipsoid

尝试通过参数名称调用它:

print g['a'] # the diameter parameter
TypeError: 'Geod' object has no attribute '__getitem__'

测试索引:

print g[0] 
TypeError: 'Geod' object does not support indexing

更新:致电print dir(g):

print dir(g)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_fwd', '_inv', '_npts', 'a', 'b', 'es', 'f', 'fwd', 'initstring', 'inv', 'npts', 'sphere']

【问题讨论】:

  • 为什么它需要有一个__getitem__ 呢?执行print dir(obj) 以查看其可用的属性。
  • 什么是“对象”???
  • @danodonovan:大概是pyproj.Geod..的一个实例
  • 这个项目是由一个C库支持的,很可能你要找的数据根本没有暴露出来。
  • 谢谢马丁。了解__getitem__ 和类属性的好方法。

标签: python class proj


【解决方案1】:

您在寻找getattr 内置函数吗?

【讨论】:

  • 就是这样!首先使用dir(g) 来验证属性的名称,然后我做了print getattr(g,'a'),这给了我想要的东西。感谢 Martijn 和 Michael!
  • 但是,这相当于print g.a。您只需要 getattr 在将属性名称作为字符串并且需要动态检索它的情况下。如果您已经知道它被称为 a,只需使用点符号即可。
  • 哎呀,是的!这太妙了。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2013-05-12
  • 2013-03-17
  • 2015-10-26
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
相关资源
最近更新 更多