Understanding namedtuple Class Utilities
00:00 In the previous lesson, I showed you the lesser-used optional arguments to the named tuple factory. In this lesson, I’m going to show you some of the lesser-used utilities that are included in your constructed named tuple classes.
00:13 Every named tuple class that you create automatically has some utility methods and attributes attached to it. To avoid some clashes with your fields, these utilities all begin with an underscore.
00:24 There are both methods and attributes on the class. The methods allow you to construct new named tuple instances from the class using an iterable for the field values, generate a dictionary from your named tuple instance, and generate a new named tuple with a change in one of the fields.
00:43 This is to replace the fact that you can’t edit the tuple, as it’s immutable. There are also two attributes on the class. The first contains the name of the fields, and the second contains the value of any defaults.
Let me call
._replace(). Note that this returns an object. The value of
p is unchanged. The new value has an age of 84 instead of 83, because that’s what I called
._replace() with. Now I’m going to actually replace
p … because I reassigned it. By calling the
id() again, you can see that it’s a different object. This isn’t the original one, but a new one. In addition to these three methods, there are also two class attributes. The first contains the name of the fields and is appropriately called
The attribute is empty if there are no default values, like in this case with the
Person named tuple. In the next lesson, I’ll be talking about the Pythonic coding approach and how named tuples can help make your code more readable.
Become a Member to join the conversation.