The magic method of Python is the predefined functions of the type _ XXX _ in Python. The biggest advantage of using the Python magic method is that python provides a simple method to make objects behave like built-in types. _ Str _ function _ str _ when the function is used to process and print the instance itself, the magic method of... Python is the predefined images in Python.
__XXX__
Type function.
The biggest advantage of using the Python magic method is that python provides a simple method to make objects behave like built-in types.
_ Str _ function
__str__
The function is used to process the output content when the instance is printed. If this function is not overwritten, an object name and memory address are output by default.
For example:
>>> class Student(object):... def __init__(self,name):... self._name = name...>>> print Student()
Output:<__main__.Student object at 0x0000000002A929E8>
.
So how can we make the output results more readable? We can override__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 result is:I'm a student, named Charlie
.
We willstr()
When a function acts on this object, it actually calls the object__str__
Function.
_
Repr _Function
__repr__
It also serializes the object,__repr__
It is more for the python compiler.__str__
It is more readable ).
We willrepr()
When a function is used to touch an object, it actually calls the function.__repr__
Function.
Andrepr()
In pairseval()
Function.eval()
A function is used to convert serialized objects into objects. The premise is that this object implements__repr__
Function.
The above paragraph is based on your own understanding and does not know right or 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 iteration. That is, list inherits from Iterable. Iterable implements the _ iter _ function.
To convert a custom object into an iteratable object, you must implement two methods:__iter__
Andnext
.
__iter__
The function returns an object. It will be called continuously during iterationnext
The function obtains the next value until it is captured.StopIteration
Stop.
What is written in the course by Dr. Liao Xuefeng?__next__
METHOD. I don't 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 implementation__iter__
Function implementation object iteration.
So how can we retrieve elements from objects by subscript.
This is through the implementation of object__getitem__
Method.
Let's take a look