I\'ve recently read about the getattr() function. The problem is that I still can\'t grasp the idea of its usage. The only thing I understand about getattr()
is
getattr(object, 'x')
is completely equivalent to object.x
.
There are only two cases where getattr
can be useful.
object.x
, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming.object.y
will raise an AttributeError
if there's no y
. But getattr(object, 'y', 5)
will return 5
.