Fluent Python Study Note #1
Named Tuple and Python Data Model. Fill the knowledge gap as a Python developer.
Fluent Python in an efficient way. I am following the book “Fluent Python” and filling the knowledge gap. It is a thick book with 21 chapters and more than 700 pages. Hopefully, the quick study note can help more people to sharpen Python skills.
Named Tuple
This is a less known type. We may have used list and tuple too much, as they are just too handy. We usually use a tuple to record information. For example, we have a list of student and each student has a name, age, gender. We usually do is the following.
We have a specific order to organise the data in our tuples. But I believe we all have the same moment when we need to double-check the order to retrieve specific data in the tuple. Or we may get confused when debugging with those tuple records.
We could use class, but for simple records, it can be an overkill. In this case, we could use “namedtuple”.
It’s almost like creating a very simple class with one line of code. We then can use the filed to access the data within the record and the order won’t matter in this case.
Python Data Model
One of the reasons why Python is easy to use is because of language consistency. For example, as long as it’s a list-like object, we can use the function “len” to get the size of if. Our user-defined class can enjoy such features when we implement special methods, such as “__len__”.
For example, we may have a class school with two special methods implemented, “__len__” and “__getitem__”. Now we can do the following.
Using the function “len” to get the size of the school and using the function choice to randomly pick up a student.
Slice the school just like a list.
Sort the school just like a list.
Other Useful Special Functions
__repr__: when we print the object, this is what will be called.
__add__: for doing plus
__mul__: for doing times
__bool__: when check with “if”
If you are new to Python, check the following link out.