Tutorial Study Image

Python getattr()

内置函数 getattr() 用于获取指定对象的属性值。如果属性不存在,则返回默认值。


getattr(object, name[, default]) #Where object,name shows object name and attribute name respectively.

语法如下


object.name
 

getattr() 参数

对于参数,我们可以直接从控制台在程序中输入属性名。我们还可以设置一些默认值,以防属性缺失,这使我们能够完成一些不完整的数据。

参数 描述 必需/可选
object  要返回其指定属性值的对象 必需
name 包含属性名称的字符串 必需
default 未找到指定属性时返回的值 可选

getattr() 返回值

getattr() 函数的默认值选项有助于访问不属于对象的任何属性。

输入 返回值
属性 给定对象的指定属性的值
无属性 默认值
 如果未找到属性且没有默认值  AttributeError 异常

Python 中 getattr() 方法的示例

示例 1:getattr() 在 Python 中如何工作?


class Person:
    age = 30
    name = "James"
pers = Person()
print('The age is:', getattr(pers, "age"))
print('The age is:', pers.age)
 

输出

The age is: 30
The age is: 30

示例 2:当未找到指定属性时 getattr()


class Person:
    age = 30
    name = "James"
pers = Person()

# when default value is provided
print('The sex is:', getattr(pers, 'sex', 'Male'))

# when no default value is provided
print('The sex is:', getattr(pers, 'sex'))
 

输出

The sex is: Male
AttributeError: 'Person' object has no attribute 'sex'

示例 3:getattr() 引发属性错误


class GfG :
    name = "GeeksforGeeks"
    age = 24
  
# initializing object
obj = GfG()
  
# use of getattr
print("The name is " + getattr(obj,'name'))
  
# use of getattr with default
print("Description is " + getattr(obj, 'description' , 'CS Portal'))
  
# use of getattr without default
print("Motto is " + getattr(obj, 'motto'))
 

输出

The name is GeeksforGeeks
Description is CS Portal

AttributeError: GfG instance has no attribute 'motto'