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__(), but len(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:

  1. Numerical operations:

    • we can overwrite numerical operations such as __abs__, __add__, __mul__
    • useful for example when working with Vectors
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import math

class Vector:

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __repr__(self):
        return f'Vector({self.x!r}, {self.y!r})'
	# !r gets the standard representation

    def __abs__(self):
        return math.hypot(self.x, self.y)

    def __bool__(self):
        return bool(abs(self))
    
    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Vector(x, y)

    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)
1
2
3
4
>>> v1 = Vector(2, 4)
>>> v2 = Vector(2, 1)
>>> v1 + v2
Vector(4, 5)
  1. 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
  2. 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 invoke x.__len__(), and if that returns 0, it is falsy

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.