1. Python Data Model

While coding with any framework, you spend a lot of time implementing methods that are called by the framework. The same happens when you leverage the Python data model. The Python interpreter invokes special methods to perform basic object oper‐ ations, often triggered by special syntax. The special method names are always written with leading and trailing double underscores (i.e., getitem ).

For example, the syntax obj[key] is supported by the getitem special method. In order to evaluate mycollection[key] , the interpreter calls mycollection.__getitem(key)

The special method names allow your objects to implement, support, and interact with basic language constructs such as:

  • Iteration

  • Collections

  • Attribute access

  • Operator overloading

  • Function and method invocation

  • Object creation and destruction

  • String representation and formatting

  • Managed contexts (i.e., with blocks)

the len and getitem implementations can hand off all the work to a list object

2. Special Methods — dunder methods

Python Data Model - 图1

The first thing to know about special methods is that they are meant to be called by the Python interpreter, and not by you. You don’t write myobject.len() . You write len(my_object) and, if myobject is an instance of a user-defined class, then Python calls the __len instance method you implemented.

If you need to invoke a special method, it is usually better to call the related built-in function (e.g., len , iter , str , etc). These built-ins call the corresponding special method, but often provide other services and—for built-in types—are faster than method calls.

3. Special method — repr

String Representation.
The repr special method is called by the repr built-in to get the string representation of the object for inspection. If we did not implement repr , vector instances would be shown in the console like .
The string returned by __repr__ should be unambiguous and, if possible, match the source code necessary to recreate the object being represented. — %r打印的,可以直接用来重新build该对象,语法一致

Contrast repr with str , which is called by the str() constructor and implicitly used by the print function. str should return a string suitable for display to end users.

If you only implement one of these special methods, choose repr , because when no custom str is available, Python will call repr as a fallback.

In Python, there are two builtin functions for turning an object into a string: str vs. repr.

  • __repr__ goal is to be unambiguous

  • __str__ goal is to be readable

repr conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

A good explanation

4. Overview of Special Methods

Python Data Model - 图2

Python Data Model - 图3
Python Data Model - 图4

len Is Not a Method

No method is called for the built-in objects of CPython: the length is simply read from a field in a C struct.

Last — used module

1. collections.namedtuple

namedtuple(typename, field_names, , verbose=False, rename=False, module=None)
*Returns a new subclass of tuple with named fields
.

  1. >>> Point = namedtuple('Point', ['x', 'y'])
  2. >>> Point.__doc__ # docstring for the new class
  3. 'Point(x, y)'
  4. >>> p = Point(11, y=22) # instantiate with positional args or keywords
  5. >>> p[0] + p[1] # indexable like a plain tuple
  6. 33
  7. >>> x, y = p # unpack like a regular tuple
  8. >>> x, y
  9. (11, 22)
  10. >>> p.x + p.y # fields also accessible by name
  11. 33
  12. >>> d = p._asdict() # convert to a dictionary
  13. >>> d['x']
  14. 11
  15. >>> Point(**d) # convert from a dictionary
  16. Point(x=11, y=22)
  17. >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
  18. Point(x=100, y=22)

2. random.choice

choice(seq) method of random.Random instance
Choose a random element from a non-empty sequence.

3. sorted

sorted(iterable, /, , key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

A custom* key function can be supplied to customize the sort order
, and the
reverse flag can be set to request the result in descending order.