Magic methods for classes in Python

Source: Internet
Author: User

Objective: To learn the magic methods of class in python to improve the efficiency of programming.


Environment: Ubuntu 16.4 python 3.5.2


Learning class is bound to come into contact with its magic methods, such as commonly used __init__, the form is preceded by a double underline. In addition to this necessary, there are other useful methods, the following is about to introduce.

Method of Operation Magic:

__add__ as +

__sub__ AS-

__mul__ as *

__truediv__ AS/

__floordiv__ AS//

__mod__ as%

__pow__ as * *

__and__ as A &

__xor__ as ^

__or__ used as |

To illustrate:

Class Specialstring:def __init__ (Self, cont): Self.cont = Cont def __truediv__ (self, Other): line = ' = ' * Len (Other.cont) return Rn.join ([Self.cont, Line, other.cont]) spam = specialstring (' spam ') Hello = Specialstring (' Helo world! ') Print (Spam/hello) # results >>>spam============hello world!>>>

x + y is equivalent to x.__add__ (y), but if X does not have a __add__ method, and X and Y are different classes, then it checks if Y has __radd__, is represented as y.__radd__ (x), does not appear typeerror, and all Megic Methods all have R methods.


Compare Magic methods:

__lt__ as a <

__le__ as <=

__eq__ as = =

__ne__ as! =

__gt__ as a >

__ge__ as >=

If the __ne__ does not exist, the direction of the __eq__ is returned.

To illustrate:

class specialstring:    def __init__ (Self, cont):         self.cont = cont             def __gt__ (self, other):         for index  in range (Len (other.cont)  + 1):             result = other.cont[:index] +  ' > '  + self.cont             result +=  ' > '  + other.cont[ Index:]            print (Result)          spam = specialstring (' spam ') eggs = specialstring (' eggs ') spam  > eggs# result>>>>spam>eggse>spam>ggseg>spam>gsegg>spam> Seggs>spam>>&gT; a magic method similar to a container: __len__ used as  len () __getitem__  as an index __setitem__  as an allocation index __delitem__  as a drop index __iter__   used as an iterative object __contains__ as an in illustration: class vaguelist:    def __init__ (self,  Cont):        self.cont = cont             def __getitem__ (Self, index):         return self.cont[index + random.randint ( -1, 1)]         def __len__ (self):         return  random.randint (0, len (Self.cont)  * 2)          Vague_list = vaguelist ([' A ',  ' B ',  ' C ',  ' D ',  ' E ']) print (len (vague_list)) print (len (vague_list)) Print (vague_list[2]) print (vague_list[2]) #result >>>22CD>>>

Reference Document Source: Sololearn


This article is from the "Rickyhul" blog, make sure to keep this source http://rickyh.blog.51cto.com/10934856/1952167

Magic methods for classes in Python

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.