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
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.
4. Overview of Special Methods
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.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
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.