Python中的getattr()函数详解:,__getattr__,Python中的ge


Python中的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.


解释的很抽象 告诉我这个函数的作用相当于是


object.name

getattr(object,name)

其实为什么不用object.name而有的时候一定要用getattr(object,name),主要是由于这里的name有可能是变量,我们不知道这个name到底是什么,


只能用getattr(object,name)去获得。

实例:

def info(object,spacing=10,collapse=1):

"""Print methods and doc strings.

Takes module, class, list, dictionary, or string."""


methodList=[method for method in dir(object) if callable(getattr(object,method))]

processFunc=collapse and (lambda s: ‘‘.join(s.split())) or (lambda s:s)

print "\r\n".join(["%s%s"%(method.ljust(spacing),processFunc(str(getattr(object,method).__doc__)))for method in methodList])


if __name__==‘__main__‘:

print info.__doc__

print info([])


理论上, getattr 可以作用于 元组,但是由于元组没有方法,所以不管你指定什么属性名称 getattr 都会引发一个异常。getattr()可以作用于


内置数据类型也可以作用于模块。

getattr()三个参数,第一个是对象,第二个是方法,第三个是可选的一个缺省的返回值。如果第二个参数指定的属性或方法没找到则返回这个缺省


值。


getattr()作为一个分发者:


import statsout


def output(data,format=‘text‘):

output_function=getattr(statsout,‘output_%s‘%format,statsout.output_text)

return output_function(data)


Python中的getattr()函数详解:

相关内容

    暂无相关文章

评论关闭