Fluent Python Charpter 1.2

Fluent Python Charpter 1.2

How Special Methods Are Used

  1. 对于我们自定义的类,我们已经知道built-in functions是如何使用自定义的special methods。那么对于已经定义好的built-in types呢?这就跟解释器有关了。但是可以确定的是对内建类型使用内建函数一定是比我们显式定义的special methods快很多。例如Cpython中的built-in types都已经编译了。

  2. 通常情况下,不需要自定义special methods,除非是自研library需要我们自定义数据类型或者使用library需要我们重写special method的。

Emulating Numeric Types

再来个vector的例子来体现更多的快乐。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> class Vector:
>>> def __init__(self, x, y):
>>> self.x = x
>>> self.y = y
>>> def __repr__(self):
>>> return 'Vecotr({}, {})'.format(self.x, self.y)
>>> def __str__(self):
>>> return self.__repr__()
>>> def __add__(self, v):
>>> x = self.x + v.x
>>> y = self.y + v.y
>>> return Vector(x, y)
>>> v = Vector(0, 1)
>>> v += Vector(-1, 2)
>>> v
  1. ___repr__定义了