The Magic method of Python is those predefined images in Python.
__XXX__
Type of function.
The biggest advantage of using Python's Magic method is that Python provides a simple way for objects to behave like built-in types.
__str__ function
__str__
function is used to process the output of the print instance itself. If the function is not overwrite, the default output is an object name and memory address.
For example:
>>> class Student (object): ... def __init__ (self,name): ... Self._name = name...>>> Print Student ()
Output: <__main__.Student object at 0x0000000002A929E8>
.
So how do we make the results of the output more readable? We can overwrite the __str__
function. For example
>>> class Student (object): ... def __init__ (self, name): ... Self._name = Name ... def __str__ (self): ... return "I ' m a student, named%s"% self._name...>>> print student ("Charlie")
The output is: I'm a student, named Charlie
.
When we apply a str()
function to the object, it is actually called the function of the object __str__
.
_repr_ function
__repr__
The object is also serialized, but __repr__
it is more for the Python compiler to see. __str__
more readability (readable).
When we use a repr()
function to touch an object, the function is actually called __repr__
.
And repr()
paired is the eval()
function. The eval()
function is to re-convert the serialized object to an object. The premise is that the object implements the __repr__
function.
The above paragraph is based on your own understanding, do not know right and wrong.
>>> item = [1,2,3]>>> repr (item) ' [1, 2, 3] ' >>> Other_item = eval (repr (item)) >>> Other_item[1]2
__iter__ function
We often use for...in for list or tuple ... To iterate. That's the list inherited from Iterable. Iterable implements the __ITER__ function.
To turn a custom object into an iterative object, you must implement two methods: __iter__
and next
.
__iter__
The function returns an object. The iteration will constantly call the next
function to get the next value until the capture StopIteration
stops.
Liaoche teacher in the course of writing is the __next__
method, do not know why.
Class Fib (object): def __init__ (self): self.a, self.b = 0, 1 def __iter__ (self): return self def Next (self): self.a, self.b = self.b, SELF.A + self.b if SELF.A > 10000: raise Stopiteration return Self.afor i in Fib (): Print I
__getitem__ function
The above implements __iter__
an iterative iteration of the object by implementing a function.
So how do you implement an object to take out elements by subscript?
This is done by implementing the object's __getitem__
method.
We're going to give a