python内置函数5-getattr()
来源:互联网 发布:知秋一生所爱吉他谱 编辑:程序博客网 时间:2024/05/16 09:37
Help on built-in function getattr in module __builtin__:
getattr(...)
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
中文说明:
实现反射机制,可以通过字符串获取方法实例。
本函数实现获取对象object的属性,属性由name来表示,就是属性名称的字符串。
参数default是可选的参数,当获取对象的属性不存在时,就返回此值;如果没有提供此参数,同时在对象属性里也找不到,不会抛出异常AttributeError。
class A:
def __init__(self):
self.a = 'a'
def method(self):
print "method print"
a = A()
print getattr(a, 'a', 'default') #如果有属性a则打印a,否则打印default
a
print getattr(a, 'b', 'default') #如果有属性b则打印b,否则打印default
default
print getattr(a, 'method', 'default')#如果有方法method,否则打印其地址,否则打印default
<bound method A.method of <__main__.A instance at 0x7f7d5204b8c0>>
print getattr(a, 'method', 'default')()#如果有方法method,运行函数并打印None否则打印default
method print
None
>>> class Foo:
... def __init__(self):
... self.x=100
...
>>> foo=Foo()
>>> print(getattr(foo,'x'))
100
>>> print(foo.x)
100
>>> print(getattr(foo,'y',200))
200
- python内置函数5-getattr()
- python 内置函数getattr
- PYTHON getattr setattr hasattr delattr内置函数
- Python标准库:内置函数getattr(object, name[, default])
- 利用Python内置函数getattr轻松实现分发模式
- 四.python面试题 内置函数instance getattr setattr hasattr
- python内置函数getattr(),hasattr(),setattr(),delattr()【属性相关】
- python 内置函数isinstance(),hasattr(),getattr(),setattr()的介绍
- Python的getattr函数
- python中常用的内置函数filter,setattr,delattr,getattr,hasattr
- Python中的getattr()函数 (一)
- Python中的getattr()函数 (二)
- Python中的getattr()函数详解
- Python中的getattr()函数详解
- Python中的getattr()函数详解
- Python中的getattr()函数详解
- Python中的getattr()函数详解
- Python中的getattr()函数详解
- 336. Palindrome Pairs
- 北航2009年计算机复试上机
- oracle 赋予用户权限
- WebService(5):
- CSS3-伸缩布局介绍
- python内置函数5-getattr()
- MYSQL管理之主从同步管理
- Java中的多线程
- linux 任务管理总结
- 深度学习发展历史
- 字符串匹配算法
- 帧动画的简单使用
- override和overload的区别
- HDU