Working with Object Attributes

Besides the usual way of accessing object attributes using dot notation, Python provides four special functions: getattr, setattr, delattr, and hasattr.

From the names, it's easy to understand that the first three are responsible for getting, setting, and deleting an attribute, respectively. The last one checks whether an attribute with the specified name exists in the object or not.

In all these functions, the first two arguments are the object and the attribute name as a string. In setattr, you also need to pass the new value for the attribute.

In practice, using these functions is quite rare, but they can be very handy in certain situations, so it's worth keeping them in mind.

Comments (0)

Leave a comment