简体   繁体   English

从python中的对象获取getattr属性

[英]get attribute with getattr from a object in python

I have an object p ( liblas.point.Point ) with several attributes 我有一个带有几个属性的对象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

I have a problem with get_point_source_id() where 我有一个问题get_point_source_id()在哪里

p.get_point_source_id()
20

but when i use getattr i got this message 但是当我使用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()'

The parentheses are almost certainly not part of the attribute name. 括号几乎肯定不是属性名称的一部分。 Get rid of them when calling getattr() . 调用getattr()时摆脱它们。 Then you need to call the method: 然后你需要调用方法:

attr_name = pattr[letter]
if not attr_name.endswith("()"):
  print getattr(p, attr_name)
else:
  print getattr(p, attr_name[:-2])()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:如何用getattr得到一个object属性属性? - Python: How to get attribute of attribute of an object with getattr? Python - Kivy:AttributeError:&#39;super&#39;对象在尝试获取self.ids时没有属性&#39;__getattr__&#39; - Python - Kivy: AttributeError: 'super' object has no attribute '__getattr__' when trying to get self.ids 如何在python中使用getattr获取Django模型的外键对象的属性? - How to get attribute of a django model's foreign key object using getattr in python? Kivy:无法从python代码中添加按钮“ AttrErr:&#39;super&#39;对象没有属性&#39;__getattr__” - Kivy: Can't add button from python code “AttrErr: 'super' object has no attribute '__getattr__” Python Kivy 返回 'AttributeError: 'super' object 没有属性 '__getattr__'' - Python Kivy returning 'AttributeError: 'super' object has no attribute '__getattr__'' &#39;super&#39;对象在python3中没有属性&#39;__getattr__&#39; - 'super' object has no attribute '__getattr__' in python3 AttributeError: &#39;super&#39; 对象在 python 中没有属性 &#39;__getattr__&#39; - AttributeError: 'super' object has no attribute '__getattr__' in python python kivy AttributeError:“超级”对象没有属性“ __getattr__” - python kivy AttributeError: 'super' object has no attribute '__getattr__' Python getattr() 以另一个属性作为默认值 - Python getattr() with another attribute as the default 无法从 kivy 文件访问特定 ID 到我的 python 错误“AttributeError: 'super' object 没有属性 '__getattr__'” - Unable to access a particular id from kivy file to my python ERROR "AttributeError: 'super' object has no attribute '__getattr__'"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM