Preface:
In this paper all ideas and test code is based on python3.
Content:
1. What is the function of magic, magic function __getitem__ application in python.
Affect the data model and data model of this design of the python 2.python
3.python commonly used magic function
4. See characteristics from the magic function len () method
5. Magic function knowledge Summary
A python's magic function
1. What is the magic function?
- Magic Python function is defined, beginning with __, __ end, shaped like __fun __ () function is generally used to have good definition.
- Some use this function, allows us to customize the class has more powerful features.
- Magic general implicit function calls, we do not need to show the call. (Ie python interpreter to help us call implementation)
2. How to use the magic function?
Example: We have established a company class, which has staff list of attributes. All employees need to print cycle.
Common methods are:
1 class Company: 2 def __init__(self,employee_list): 3 self.employee=employee_list 4 user_list=['ttr1','ttrr2','ttrr3'] 5 company=Company(user_list) 6 for i in company.employee: 7 print(i)
If we python with a built-in function magic words:
user_list=['ttr1','ttrr2','ttrr3'] company=Company(user_list) class Company_Magic: def __init__(self,employee_list): self.employee_list=employee_list def __getitem__(self, item): return self.employee_list[item] company2=Company_Magic(user_list) for i in company2: print(i)
Difference: A second object directly for loop, the first attribute of the object inside of a (list) is circulated.
Company_Magic class is the second generation of the object, there may be an iterative this feature.
Because when __getitem__ help us achieve a logical, every time we realize the for loop, for this will go company2 __getitem__ method (actually find someone to another iterative method) object and pass 0, 1, 2, ... until the end and then throw an exception. This is a function of the interpreter to help us achieve.
ps. __getitem__ Think about if this function is not passed no matter what item reported abnormal happens?
Two python data model and data model design pattern characteristic imparting python
1. What is the data model?
In fact, the data model is a description of the Python frame, which regulate their own language construct this interface module, these modules include but are not limited to sequence iterator, functions, and the like.
The concept of a magic function is the data model. java often called magic methods, python often called the data model.
2. The impact of the data model for python
- Magic function does not belong to the class that defines it, but some of the features like enhanced.
- The realization of a certain magic function, some operations will become particularly simple.
- We can use the magic function to achieve the flexibility to design class we need.
This is a very important need to understand python class some features can be flexibly designed , as long as it follows the coding of a particular protocol (magic function).
Three magic python commonly used functions
__init__: the most commonly used.
__str__: print function is called; this function must return to the magic string, otherwise throw an exception.
(I remember most beginners start calling any way mongodb python object to the return of the data print out the string has been no problem, but do processing time has been saying malformed data, because data objects pass back to do __str__ process.)
__len__: You can use len () function of the object. In dict, list other types also implement this method.
In pycharm, the input dict (), defined with ctrl + B dict the jump, which can be seen having a magic method dict. Or ({}) may also be seen by dir.
There are many more important magic methods such __setattr __ (), __ getattr __ (), __ setitem __ (), __ getitem __ (), __ iter __ () super multi-function magic simplify our programming.
Four Uses __len__ see magic function generally do what things?
Three, we see the contents of the magic function definition dict () in __len __ () is defined as empty, list () too.
In fact, we see here is only the equivalent of an interface definition only, the real implementation is in cpython in.
For the definition of the source position in the list directory Python include/listobject.h
the following code:
typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_item contains space for 'allocated' elements. The number * currently in use is ob_size. * Invariants: * 0 <= ob_size <= allocated * len(list) == ob_size * ob_item == NULL implies ob_size == allocated == 0 * list.sort() temporarily sets allocated to -1 to detect mutations. * * Items must normally not be NULL, except during construction when * the list is not yet visible outside the function that builds it. */ Py_ssize_t allocated; } PyListObject;
Which ob_item
is a pointer to a list element pointer array, list [0] i.e. ob_item [0], allocated
the spatial size of the list. In the PyObject_VAR_HEAD
middle, with a ob_size
variable.
The following is a directory Python include/object.h
relevant code:
#define PyObject_VAR_HEAD PyVarObject ob_base; ... ... typedef struct { PyObject ob_base; Py_ssize_t ob_size; /* Number of items in variable part */ } PyVarObject;
ob_size
Variable is the length of objects stored, so each call _ len _ () method when the return is a variable that has been stored well,
Five summary
- Magic functions are built in the front of a method of __
- Magic show called function is not required, python syntax itself implicitly calls the magic function
- Magic functions and inheritance object does not exist, any object can be defined magic function
- Magic functions allow various types of python organized, let the object data types, such as adding a type of iterative
- __str __ \ __ repr __ \ __ add__ so a variety of well-known popular magic function makes the code more pythonic
- In fact, the python interpreter will likely increase by a lot of efficiency, allows developers increased flexibility