Chap1. The Python Data Model
The Python interpreter invokes special methods to perform basic object operations, often triggered by special syntax.
e.g. In order to evaluate my_collection[key],the interpreter calls my_collection.__getitem__(key)
magic method is slang for special method
Dunder , i.e.
__*__shortcut for “double underscore before and after“
advantages using special methods to leverage the Python Data Model
- Users of your classes don’t have to memorize arbitrary methods name for standard operations(like
len(my_object)) 类的使用者不需要额外记住一些标准操作的类方法 - easier to benefit from the rich Python standard library and avoiding reinventing the wheel(like
random.choice. this will be shown below)和Python标准库联动避免重复造轮子
Now let’s paly poker 🧐 But first we need a deck of cards
1 | import collections |
collections.namedtuple is used to build classes of objects that are just bundles of attributes with no custom methods, like a database record.
namedtuple具名元组用来构造只有属性、没有自定义方法的类,就像数据库表的记录
对于具名元组的元素,既可以用索引获取,也可以像获取对象属性一样去点访问
1 | luck_card = Card('12', 'spades') |
By implementing the special methods __len__ and __getitem__, FrenchDeck behaves like a standard Python sequence. 实现了这两个魔术方法,FrenchDeck将表现出标准的Python序列的特性
1 | deck = FrenchDeck() |
More usages about special methods:
- Emulating Numeric Types
- String Representation of an Object
- Boolean Value of an Object
Here is a simple two-dimensional vector class
1 | import math |
默认情况下,用户定义的类都是永真,除非类实现了__bool__和__len__
一般情况下,bool(x)调用x.__bool__(),如果__bool__没有实现,尝试调用x.__len__,若len返回0,则bool(x)返回False
这里若向量的大小为0,则返回Flase