![](/img/trans.png)
[英]Python: How to get attribute of attribute of an object with getattr?
[英]get attribute with getattr from a object in python
我有一个带有几个属性的对象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()'
括号几乎肯定不是属性名称的一部分。 调用getattr()
时摆脱它们。 然后你需要调用方法:
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.