Chapter 1 The Python Data Model
- Python data model describes the API that you can use to make your own objects play well with the most idiomatic language features;
- The Python interpreter invokes special methods to perform basic object operations,often triggered by special syntax;
Special methods are meant to be called by the Python interpreter,and not by you;
Normally,your code should not have many direct calls to special methods;
The only special method that is frequently called by user code directly id__init__
,to invoke the initializer of the superclass in your own__init__
implementation.
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). - The special method names are always written with leading and trailing double underscores(i.e.,
__getitem__
);
The special methods are also known as dunder methods; collections.namedtuple
Since Python 2.6,namedtuple
can be used to build classes of objects that are just bundles of attributes with no custom methods,like a database record.random.choice
gets a random item from a sequence.abs
built-in function returns the absolute value of integers and floats,and the magnitude ofcomplex
numbers;__repr__
special method is called by therepr
built-in to get the string representation of the object for inspection;bool(x)
returns True or False;len(x)
runs very fast when x is an instance of a built-in type;
Because no method is called for the built-in objects of CPython: the length is simply read from a field in a C struct.By implementing special methods, your objects can behave like the built-in types,enabling the expressive coding style the community considers Pythonic
(中文大概是:Python化风格);Python object provides usable string representations of itself,one used for debugging and logging,another for presentation to the end users; That is why the special methods
__repr__
and__str__
exist in the data model;
(__repr__
is for developers,__str__
is for customers)