Python learning notes-magic method, making custom classes more like built-in types

Source: Internet
Author: User
Tags iterable
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 iterationnextThe function obtains the next value until it is captured.StopIterationStop.
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.