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

猜你喜欢

转载自blog.csdn.net/XXJ19950917/article/details/81331152