Detailed explanation of Python operator heavy load instance code sharing

Source: Internet
Author: User
Tags access properties
This article describes how to reload Python operators and related information about the instance code. For more information, see the next article, for more information, see

Python operator overload

The Python language provides the operator overload function, enhancing the language flexibility, which is somewhat similar and different from C ++. In view of its particularity, we will discuss Python operator overloading today.

The Python language provides many magic methods, and its operator overload is implemented by rewriting these Python built-in magic methods. These magic methods start and end with double underscores (_ X _). python intercepts operators through this special naming method to implement overloading. When Python's built-in operations are applied to class objects, Python searches for and calls the method specified in the object to complete the operation.

Class can overload addition and subtraction operations, printing, function calls, indexing and other built-in operations, operator overloading so that our object behavior is the same as the built-in object. Python automatically calls this method when calling the operator. for example, if the class implements the _ add _ method, this method is called when the class object appears in the + operator.

Methods for overloading common operators


Method name

Reload description

Operator call method

_ Init __

Constructor

Object creation: X = Class (args)

_ Del __

Destructor

X object reclaim

_ Add _/_ sub __

Addition and subtraction

X + Y, X + = Y/X-Y, X-= Y

_ Or __

Operator |

X | Y, X | = Y

_ Repr _/_ str __

Print/convert

Print (X), repr (X)/str (X)

_ Call __

Function call

X (* args, ** kwargs)

_ Getattr __

Attribute reference

X. undefined

_ Setattr __

Attribute assignment

X. any = value

_ Delattr __

Attribute deletion

Del X. any

_ Getattribute __

Attribute acquisition

X. any

_ Getitem __

Index operations

X [key], X [I: j]

_ Setitem __

Index assignment

X [key], X [I: j] = sequence

_ Delitem __

Index and Shard deletion

Del X [key], del X [I: j]

_ Len __

Length

Len (X)

_ Bool __

Boolean test

Bool (X)

_ Lt __, _ gt __,

_ Le __, _ ge __,

_ Eq __, _ ne __

Specific comparison

X Y, X <= Y, X> = Y,

X = Y, X! = Y

Note: (lt: less than, gt: greater,

Le: less equal, ge: greater equal,

Eq: equal, ne: not equal

)

_ Radd __

Addition on the right

Other + X

_ Iadd __

Field (enhanced) addition

X + = Y (or else _ add __)

_ Iter __, _ next __

Iteration

I = iter (X), next ()

_ Contains __

Member relationship test

Item in X (X is any iteratable object)

_ Index __

Integer

Hex (X), bin (X), oct (X)

_ Enter __, _ exit __

Environment Manager

With obj as var:

_ Get __, _ set __,

_ Delete __

Descriptor attributes

X. attr, X. attr = value, del X. attr

_ New __

Create

Create an object before _ init _

The following describes how to use common operators and methods.

Constructor and Destructor: __init _ and _ del __

They are mainly used to create and recycle objects. When an instance is created, the _ init _ constructor is called. When an instance object is withdrawn, the destructor _ del _ is automatically executed.

>>> class Human(): ...   def __init__(self, n): ...     self.name = n ...       print("__init__ ",self.name) ...   def __del__(self): ...     print("__del__") ...  >>> h = Human('Tim') __init__ Tim >>> h = 'a' __del__

Addition and Subtraction: __add _ and _ sub __

By reloading these two methods, you can add the +-operator operation on a common object. The following code demonstrates how to use the +-operator. if The _ sub _ method in the code is removed, an error occurs when the minus sign operator is called.

>>> class Computation(): ...   def __init__(self,value): ...     self.value = value ...   def __add__(self,other): ...     return self.value + other ...   def __sub__(self,other): ...     return self.value - other ...  >>> c = Computation(5) >>> c + 5 10 >>> c - 3 2

String expression of the object: __repr _ and _ str __

Both methods are used to represent the string expression of the object: the print (), str () methods call the _ str _ method, print (), str () method () and the repr () method call the _ repr _ method. As shown in the following example, when two methods are defined at the same time, Python will first search and call the _ str _ method.

>>> class Str(object): ...   def __str__(self): ...     return "__str__ called"   ...   def __repr__(self): ...     return "__repr__ called" ...  >>> s = Str() >>> print(s) __str__ called >>> repr(s) '__repr__ called' >>> str(s) '__str__ called'

Index value and value assignment: __getitem __, _ setitem __

By implementing these two methods, you can take values and assign values to an object in the form of X [I], or use slice operations on the object.

>>> class Indexer:   data = [1,2,3,4,5,6]   def __getitem__(self,index):     return self.data[index]   def __setitem__(self,k,v):     self.data[k] = v     print(self.data) >>> i = Indexer() >>> i[0] 1 >>> i[1:4] [2, 3, 4] >>> i[0]=10 [10, 2, 3, 4, 5, 6]

Set and access properties :__ getattr _, _ setattr __

We can overload _ getattr _ and _ setattr _ to intercept access to object members. _ Getattr _ is automatically called when a member does not exist in the access object. The _ setattr _ method is called when an object member is initialized. that is, the _ setattr _ method is called when _ dict _ item is set. An example is as follows:

class A():   def __init__(self,ax,bx):     self.a = ax     self.b = bx   def f(self):     print (self.__dict__)   def __getattr__(self,name):     print ("__getattr__")   def __setattr__(self,name,value):     print ("__setattr__")     self.__dict__[name] = value  a = A(1,2) a.f() a.x a.x = 3 a.f()

The running result of the code above is as follows. it can be seen from the result that the _ getattr _ method is called when accessing the nonexistent variable x; when _ init _ is called, the value assignment operation also calls the _ setattr _ method.

__setattr__ __setattr__ {'a': 1, 'b': 2} __getattr__ __setattr__ {'a': 1, 'x': 3, 'b': 2}

Iterator object: _ iter __, _ next __

The iteration in Python can be directly implemented through the overload _ getitem _ method. See the following example.

>>> class Indexer: ...   data = [1,2,3,4,5,6] ...   def __getitem__(self,index): ...       return self.data[index] ...  >>> x = Indexer() >>> for item in x: ...   print(item) ...  1 2 3 4 5 6

The above method can achieve iteration, but it is not the best way. In Python, The _ iter _ method is first called, and then _ getitem _ is attempted __. The iteration environment is implemented by iter trying to find the _ iter _ method, which returns an iterator object. If this method is provided, Python will repeatedly call the next () method of the iterator object until a StopIteration exception occurs. If _ iter __is not found, Python will try to use the _ getitem _ mechanism. The following is an example of an iterator.

class Next(object):   def __init__(self, data=1):     self.data = data   def __iter__(self):     return self   def __next__(self):     print("__next__ called")     if self.data > 5:       raise StopIteration     else:       self.data += 1       return self.data for i in Next(3):   print(i) print("-----------") n = Next(3) i = iter(n) while True:   try:     print(next(i))   except Exception as e:     break

The program running result is as follows:

__next__ called 4 __next__ called 5 __next__ called 6 __next__ called ----------- __next__ called 4 __next__ called 5 __next__ called 6 __next__ called

It can be seen that after the _ iter _ and _ next _ methods are implemented, the object can be iterated through the for in method, or through iter () and next () method to iterate over objects.

Thank you for reading this article. I hope it will help you. thank you for your support for this site!

The above is a detailed description of the Python operator heavy load instance code sharing. For more details, please follow other articles in the first PHP community!

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.