Python Magic Method: Make custom classes more like built-in types

Source: Internet
Author: User
Tags iterable
Python's Magic method is the predefined functions in Python like the __xxx__ type.

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

The __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 put the STR () function on the object, we actually called the __str__ function of the object.


__repr__ function


__REPR__ also serializes objects, but __repr__ is more for the Python compiler to see. __STR__ is more readable (readable).


When we use the repr () function to touch an object, the call is actually the __repr__ function of the function.


Paired with Repr () is the eval () function. The eval () function converts the serialized object back 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.


The __ITER__ function returns an object. The iteration calls the next function to get the next value until the Stopiteration stop is captured.


Liaoche Teacher's tutorial is written in __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 sel F.A for  i in Fib ():    Print I


__getitem__ function


The above implements an iterative iteration of the object by implementing the __ITER__ function.


So how do you implement an object to take out elements by subscript?


This is done by implementing the __getitem__ method of the object.


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.