Python Learning Notes-Magic method to make custom classes more like built-in types

Source: Internet
Author: User
Tags iterable
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

  • Related Article

    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.