Advanced Lesson 2
Advanced Object-Oriented Programming
Chapter 5: Advanced Python type features
Named tuples
If you do not need a full class, you can sometimes create a simple data structure with attributes using namedtuple
.
Remember the coordinates in your robot project when you had to use coord[0]
and coord[1]
to represent the row
and col
respectively? You can actually use namedtuple
s to make your tuples more self-explanatory by naming coord[0]
as coord.row
and coord[1]
and coord.col
! You can even make your tuple a type (say Coordinates
!)
Hopefully the example below is self-explanatory!
>>> from collections import namedtuple
>>> Coordinates = namedtuple("Coordinates", "row col")
>>> print(type(Coordinates))
<class 'type'>
>>> position = Coordinates(4, 5)
>>> print(position)
Coordinates(row=4, col=5)
>>> print(position.row)
4
>>> print(position.col)
5
>>> print(position[0]) # This still works too!
4
>>> print(position[1])
5
>>> Coordinates(4, 5) == (4, 5) # Coordinates is still a tuple!
True