Python(Built-in Functions)之getattr()

Python(Built-in Functions)之getattr()

  • Python编程语言官方给出的Api文档解释是:
    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.

描述

  • getattr()函数用于返回一个对象属性值。

语法:

getattr(object, name[, default])

参数说明:

  • object: 对象;
  • name: 必须为字符串,对象属性;
  • default: 默认返回值,如果不提供该参数,在没有对象属性(也就是name)时,将触发AttributeError。

返回值:

  • 返回对象属性值

实例说明:

>>> class Test(object): # Test对象
...     a = 1
...
>>> test = Test() 
>>> getattr(test, 'a') # 获取属性a的值,返回值为1
1
>>> getattr(test, 'a', 2) # 如果存在属性a的值,返回值是属性a的值,默认值设置无效
1
>>> getattr(test, 'b') # 获取属性b的值, 返回AttributeError,因为不存在属性b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'b'
>>> getattr(test, 'c', 3) # 属性c的值不存在,但是设置了默认值
3
>>> getattr(test, 'c') # 默认值并不是属性c的值,请记住属性c的值不存在,返回AttributeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'c'
>>>

测试用例注意:
...后面是一个Tab键长度,第二个...直接点击Enter即可。其他的跟着操作即可

  • 所以在很多情况下为了不出现AttributeError的错误信息,需要加上默认值设置来避免AttributeError的错误出现。

额外知识:

  • Build-in Functions指的是Python编程语言的内置函数,什么是内置函数了?
  • 官方给出的解释是:

The Python interpreter has a number of functions and types built into it that are always available.

  • Python解释器内置了许多始终可用的函数和类型。换句话说,getattr()始终是可以用的。

JackDan Thinking

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值