Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Managing Attributes
00:00 In the previous lesson, I showed you the built-in functions you can use as decorators to change the behavior of methods in a class. In this lesson, I’ll focus on attributes.
00:10 Not only is Python an object-oriented language, it’s also a dynamic one, meaning you can change any object on the fly, not just at declaration time. This actually extends to methods as well, but in this lesson, I’m going to concentrate on manipulating attributes. There are built-in functions to check if an attribute exists, get them, set them, and remove them.
00:33 Back to the REPL to play with some more objects. I’ll start out with a simple class.
00:51
Now that I have an instance, I can use hasattr() to see if an attribute exists on the object.
01:00
hasattr() takes two arguments, the object to inspect and the name of the attribute. It returns True if the attribute is there,
01:11
and False if it is not. I can fetch an attribute using getattr().
01:20
And there’s her name. If I try to use getattr() on a nonexistent attribute, I get an AttributeError, which is the same as if I had attempted to get at it with dot notation.
01:34
Speaking of dot notation, seeing as that’s normally how you get at objects’ attributes, why would you use getattr() at all? Well, the value really comes from being able to name the attribute with a string.
01:45
Sometimes you want to dynamically access parts of an object. If you need to perform the same operation on several different objects, instead of copying and pasting your code, you can loop over them, calling getattr() with a string in order to get at their values.
02:00
This gives you a similar approach to the attributes on your object as you would with key-value pairs in a dictionary. If instead of getting the attribute you want to set it, you use setattr().
02:15
setattr() takes three arguments: the object, the name of the attribute, and the new value. Not sure why she’s shouting, maybe she’s excited about dynamically setting attributes.
02:28
setattr() isn’t just restricted to replacing existing attributes. You can use it to create new ones as well. This would be the truly dynamic part of Python.
02:43 My favorite acronym in computing is CRUD. That stands for Create, Read, Update, and Delete. Those are the four operations you do on data. You just saw the first three, so let’s delete some stuff.
02:57
Somewhat predictably, delattr() allows you to remove attributes.
03:04 And there it is, gone. Next up, getting information about classes and objects.
Become a Member to join the conversation.