I want to learn Python deeply.
Because I like to combine learning materials and I also like to learn from books, I have bought a book considered “a bible of Python” - Fluent Python. It contains almost 1000 pages and has really good reviews.
I will use it not only as a reference when I need to look something up, but I will slowly go through it topic-by-topic in order to learn as much about the language as possible.
I will be taking notes.
Special methods (__len__
):
- called by Python interpreter, not by user
- you don’t write
my_object.__len__()
, butlen(my_object)
and if my_object is an instance of a user-defined class, Python calls the__len__
method user defined in the object - normally your code should not have many direct calls to special methods, unless you are doing a lot of metaprogramming
- only special method often called by user is
__init__
Uses of special methods:
-
Numerical operations:
- we can overwrite numerical operations such as
__abs__
,__add__
,__mul__
- useful for example when working with Vectors
- we can overwrite numerical operations such as
|
|
|
|
-
String representation
__repr__
returns string representation of the object- without
__repr__
Python would only return<Vector object at 0x10e100070>
- best practicewhen using
__repr__
is to return the source code to recreate the object, i.e.Vector(3, 4)
- this is oriented for the developer - special method oriented for the end-user is
__str__
__repr__
goal is to be unambiguous__str__
goal is to be readable
-
Boolean value of an object
- to determine whether a value is truthy or falsy, Python uses
bool(value)
- by default, user-defined classes are truthy, unless either
__bool__
or__len__
is implemented - if there is no
__bool__
defined, Python tries to invokex.__len__()
, and if that returns 0, it is falsy
- to determine whether a value is truthy or falsy, Python uses
Python contains a lot of special methods in a lot of categories (see documentation).
By implementing special methods, your objects can behave like the built-in types.