0

我有一个具有多个属性的对象 p ( liblas.point.Point )

pattr = {
    "r": 'return_number',
    "n": 'number_of_returns',
    "s": 'get_point_source_id()',
    "e": 'flightline_edge',
    "c": 'classification',
    "a": 'scan_angle',
}

mylist = ["r", "n", "e", "c", "a"]

for letter in mylist:
    print getattr(p, pattr[letter])

1
3
0
1
-23

get_point_source_id()我在哪里有问题

p.get_point_source_id()
20

但是当我使用 getattr 时,我收到了这条消息

getattr(p, pattr["s"])
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2721, in run_code
    exec code_obj in self.user_global_ns, self.user_ns
  File "<ipython-input-81-bbad74aa3829>", line 1, in <module>
    getattr(p, pattr["s"])
AttributeError: 'Point' object has no attribute 'get_point_source_id()'
4

1 回答 1

2

括号几乎肯定不是属性名称的一部分。调用时摆脱它们getattr()。然后你需要调用方法:

attr_name = pattr[letter]
if not attr_name.endswith("()"):
  print getattr(p, attr_name)
else:
  print getattr(p, attr_name[:-2])()
于 2013-08-21T15:24:57.277 回答