python中getattr详解_Python中的getattr()函数详解:

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)

prin

你可能感兴趣的:(python中getattr详解_Python中的getattr()函数详解:)