python -- getattr

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 calling getattr(object, name) and seeing whether it raises anexception or not.)

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值