Python getattr() Function
Description
getattr() The function returns the value of an object's attribute.
Syntax
getattr syntax:
getattr(object, name[, default])
Parameters
- object -- the object.
- name -- a string, the attribute name.
- default -- the default return value. If this parameter is not provided, an AttributeError is raised when the attribute does not exist.
Return Value
Returns the value of the object's attribute.
Example
The following examples demonstrate 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, raising an exception
Traceback
(
most
recent
call
last
)
:
File
"
"
,
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 built-in function