Python getattr() 函数用法

2023-09-17 22:27:47

getattr() 方法返回对象属性的值。如果命名属性不存在,则返回默认值(如果提供),否则将引发AttributeError

语法:

getattr(object, name, default)

参数:

  1. object:需要返回其属性值的类的对象。
  2. 名称
  3. :属性的字符串名称。
  4. 违约。(可选)找不到属性时返回的值。

返回值:

  • 返回给定对象的属性值。
  • 如果未找到属性,则返回指定的默认值。
  • 如果未指定默认值,则抛出AttributeError .

下面的示例演示 getattr() 方法。

class student:
    name = 'John'
    age = 18
    
std = student() # creating object
print('student name is ', getattr(std, 'name'))
std.name = 'Bill' # updating value
print('student name changed to ', getattr(std, 'name'))

输出:

student name is John
student name changed to Bill

上面,getattr(std, 'name') 返回 std 对象的 name 属性的值,即 John 。 即使在更新属性值后,它也始终返回最新值。

如果未找到参数中指定的属性,则会引发AttributeError异常。

class student:
    name = 'John'
    age = '18'
std = student()
attr = getattr(std, 'subject')

output

Traceback (most recent call last):
    attr = getattr(std, 'subject')
AttributeError: type object 'student' has no attribute 'subject'

可以传递默认参数以避免上述错误,如果未找到属性,则返回默认值。

class student:
    name = 'John'
    age = '18'
std = student()
subject = getattr(std, 'subject', 'Not supported')
print("student's subject: ", subject)

输出:

student's subject: Not supported

如果确定对象具有属性值,则还可以使用 . 运算符来访问该属性值,而不是getattr()方法。

class student:
    name = 'John'
    age = '18'
std = student()
print('student name is ', std.name)

输出:

student name is John

下面获取内置列表对象的方法。

nums= [1, 2, 3, 4, 5]
rev = getattr(nums, 'reverse')
rev()
print(nums)

输出:

[5, 4, 3, 2, 1]