Python getattr() Function

Python 内置函数Python Built-in Functions


Description

getattr()The function is used to return the value of an object's attribute.

Syntax

getattr syntax:

getattr(object, name[, default])

Parameters

  • object -- The object.
  • name -- A string, the object attribute.
  • default -- The default return value. If this parameter is not provided, AttributeError will be triggered when there is no corresponding attribute.

Return Value

Returns the value of the object attribute.

Examples

The following example demonstrates how to use getattr:

>>>class A(object): ... bar = 1 ... >>> a = A() >>> getattr(a, 'bar') # Get the value of attribute bar 1 >>> getattr(a, 'bar2') # Attribute bar2 does not exist, triggers an exception Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'A' object has no attribute 'bar2' >>> getattr(a, 'bar2', 3) # Attribute bar2 does not exist, but a default value is set 3 >>>

Python 内置函数Python Built-in Functions

Other Extensions