getattr(object, 'x')
is completely equivalent to object.x
.
There are only two cases where getattr
can be useful.
- you can’t write
object.x
, because you don’t know in advance which attribute you want (it comes from a string). Very useful for meta-programming. - you want to provide a default value.
object.y
will raise anAttributeError
if there’s noy
. Butgetattr(object, 'y', 5)
will return5
.