码迷,mamicode.com
首页 > 编程语言 > 详细

Python getattr() 函数

时间:2020-01-04 10:55:09      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:last   object   属性   call   ack   bar   err   UNC   error   

getattr() 函数用于返回一个对象属性值。

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, bar)        # 获取属性 bar 值
1
>>> getattr(a, bar2)       # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A object has no attribute bar2
>>> getattr(a, bar2, 3)    # 属性 bar2 不存在,但设置了默认值
3
>>>

getattr(sys.modules[__name__], func_name)的含义便是找到当前文件下名称为func_name的对象(类对象或者函数对象)

Python getattr() 函数

标签:last   object   属性   call   ack   bar   err   UNC   error   

原文地址:https://www.cnblogs.com/bt14/p/12147741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!