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

0 0
原创粉丝点击