Fluent Python Data model
- By implementing the special methods (__len__, etc), it hook into built-in operations (len(), etc)
- By implementing special methods combination they build protocols (interfaces)
- By overloading the methods __add__, object participate in operations like +
- Object Customization Hooks: __getattr__
Special Methods
None of special methods is directly called. Python interpreter is the only frequent caller of most special methods.
\_\_repr\_\_: is called by repr, to get the string representation of the object for inspection. returned by \_\_repr\_\_ should be unambiguous and sometimes match the source code necessary to re-create the represented object.
\_\_str\_\_: called by the str() built-in and implicitly used by the print function. It should return a string suitable for display to end users. If \_\_repr\_\_ is user-friendly you don't need to code \_\_str\_\_
If you only implement one of them, choose, \_\_repr\_\_.
To determine whether a value x is truthy or falsy, Python applies bool(x), which returns either True or False.
By default, instances of user-defined classes are considered truthy, unless either \_\_bool\_\_ or \_\_len\_\_ is implemented.
bool(x) will call x.__bool__() and use the result. If \_\_bool\_\_ is not implemented, Python tries to invoke x.__len__(), and if that returns zero, bool returns False. Otherwise bool returns True.
Collection API
- Iterable to support for, unpacking, and ohter forms of iteration.
- Sized to support the len built-in function
- Container to support the in operator
Three important Collections:
- Sequence: formalizing the interface of built-ins like list and str;
- Mapping: implemented by dict, collections.defaultdict, etc
- Set: the interface of the set and frozenset built-in types
String/bytes representation: \_\_repr\_\_, \_\_str\_\_, \_\_format\_\_, \_\_bytes\_\_, \_\_fspath\_\_
Conversation to number: \_\_bool\_\_, \_\_complex\_\_, \_\_int\_\_, \_\_float\_\_, \_\_hash\_\_, \_\_index\_\_
Emulating collections: \_\_len\_\_, \_\_getitem\_\_, \_\_setitem\_\_, \_\_delitem\_\_, \_\_contains\_\_
Iteration: \_\_iter\_\_, \_\_aiter\_\_, \_\_next\_\_, \_\_anext\_\_, \_\_reversed\_\_
- List comprehensions and the basics of generator expressions
- Using tuples as records, versus using tuples as immutable lists
- Sequence unpacking and sequence patterns
- Reading from slices and writing to slices
- Specialized sequence types, like arrays and queues
Sequences:
- Container sequences: Can hold items of different types, including nested containers. Some examples: list, tuple, and collections.deque.
- Flat sequences: Hold items of one simple type: Some examples: str, bytes, and array.array.
A container sequence holds references to the objects it contains, while flat sequence stores the value of its contents in its own memory space, and not as distinct python objects.
特徴:
mutable vs immutable container vs flat
list: a mutable container
List comprehensions
