python -- getattr

来源:互联网 发布:勇敢的心德莱厄斯淘宝 编辑:程序博客网 时间:2024/04/29 07:27

https://docs.python.org/2/library/functions.html?highlight=getattr#getattr


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 thevalue of that attribute. For example,getattr(x,'foobar') is equivalent tox.foobar. If the named attribute does not exist,default is returned ifprovided, otherwiseAttributeError is raised.

上面的意思大致是: getattr返回Object对象的name属性值,。name必须是个字符串,如果该字符串是object的一个属性,返回结果将对应该属性的值。例如,getattr(x, 'foobar') 等效于 x.foobar。如果属性不存在,则返回default处的值,如果没有定义default,那么将产生一个AttributeError异常。

=============================================================================================

    def __init__(self, name=None, **kwargs):        if name is not None:            self.name = name        elif not getattr(self, 'name', None):            raise ValueError("%s must have a name" % type(self).__name__)        self.__dict__.update(kwargs)        if not hasattr(self, 'start_urls'):            self.start_urls = []

if  not getattr(str, '__invalid__', 'string'):

    print 'No'  # 不打印No

if not getattr(str, '__invalid__', None):

    print 'No' # 打印No


x = not getattr(str, 'string', None)  # x = True

y = not getattr(str, 'string', 'string') # y = False


=============================================================================================

hasattr(object,name)

The arguments are an object and a string. The result is True if the stringis the name of one of the object’s attributes,False if not. (This isimplemented by callinggetattr(object, name) and seeing whether it raises anexception or not.)

如果name是object的属性,则返回True,否则返回False.(它的实现是通过调用getattr函数, 然后检查是否出现异常)


0 0