python内置函数5-getattr()
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python内置函数5-getattr()相关的知识,希望对你有一定的参考价值。
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
本文出自 “大云技术” 博客,请务必保留此出处http://hdlptz.blog.51cto.com/12553181/1900157
以上是关于python内置函数5-getattr()的主要内容,如果未能解决你的问题,请参考以下文章