Python getters attributes

I vaguely remember learning about some kind of built-in function that would make the equivalent

f = lambda x: x.attr

I just imagine it or does it exist?

+5
source share
2 answers
getattr(obj, 'attr')

will get an attribute attrfrom objor raise AttributeErrorif it does not exist. You can also specify a default value:

getattr(obj, 'attr', None)

and in this case, the default value will be returned instead of throwing an exception if the attribute is not found on the object.

+3
source

All Articles