python函数回顾:getattr()
2018-04-19 08:14
295 查看
描述
getattr() 函数用于返回一个对象属性值。
语法
getattr 语法: getattr(object, name[, default])
参数
- object -- 对象。
- name -- 字符串,对象属性。
- default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
返回值
返回对象属性值。
实例
>>>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 >>>
相关文章推荐
- Python中的getattr()函数详解
- Python3 hasattr()、getattr()、setattr()、delattr()函数
- Python的hasattr() getattr() setattr() 函数
- Python中的getattr()函数详解
- Python 一些特别函数 __getitem__ __getattr__
- Python中的getattr()函数详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python中的getattr()函数详解
- python 内建函数setattr() getattr()
- python函数回顾:dict()
- 详解Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码数
- python 知识点:反射 之 getattr()实现以字符串形式导入模块和执行函数
- 详细讲述python自省函数getattr的用法
- Python中getattr函数和hasattr函数作用详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- python自省函数getattr的用法
- Python的hasattr() getattr() setattr() 函数使用方法详解
- python函数回顾:slice()
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解