Home > Backend Development > Python Tutorial > Detailed explanation of Python operator overloading example code sharing

Detailed explanation of Python operator overloading example code sharing

高洛峰
Release: 2017-03-10 09:07:10
Original
1312 people have browsed it

This article mainly introduces the relevant information for detailed explanation of Python operator overloading example code sharing. Friends who need it can refer to

Python operator overloading

Provided by Python language It has the operator overloading function and enhances the flexibility of the language. This is somewhat similar to but somewhat different from C++. In view of its special nature, today we will discuss Python operator overloading.

The Python language itself provides many magic methods, and its operator overloading is achieved by rewriting these Python built-in magic methods. These magic methods all start and end with double underscores, similar to the form of __X__. Python intercepts operators through this special naming method to achieve overloading. When Python's built-in operations are applied to a class object, Python will search for and call the specified method in the object to complete the operation.

Classes can overload built-in operations such as addition and subtraction, printing, function calls, indexing, etc. Operator overloading makes our objects behave the same as built-in objects. Python will automatically call such a method when calling an operator. For example, if a class implements the __add__ method, this method will be called when an object of the class appears in the + operator.

Common operator overloading methods


## __add__/__sub__Addition and subtraction operations X+Y, X+=Y/X-Y, X-=Y__or__Operator|X|Y, X|=Y_repr__/__str__Print/Convertprint(X) , repr(X)/str(X)__call__Function callX(*args, **kwargs)##__getattr____setattr____delattr__X.any##__getitem____setitem__##__delitem____len__ __bool____le__, __ge__, le: less equal, ge: greater equal, Field (enhanced) additionIteration##__contains__Membership Test__index__Integer value__delete__Descriptor attribute__new__Create
##Method name

Overloading description

Operator calling method

__init__

Constructor

Object creation: X = Class(args)

__del__

Destructor

X object is recovered

##Attribute reference

X.undefined

Attribute assignment

X.any=value

Attribute deletion

del

Index operation

X[key],X[i:j]

Index assignment

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

Index and shard deletion

del X[key], del X[i:j]

Length

len(X)

Boolean test

bool(X)

##__lt__ , __gt__,
__eq__, __ne__

Specific comparison

in sequence For XY, X<=Y, X>=Y,

X==Y, greater than,
eq: equal, ne: not equal

__radd__

Addition on the right side

other+X

__iadd__

X+=Y(or else __add__)

__iter__, __next__

I=iter(X), next( )

item in X (X is any iterable object)

hex(X), bin(X), oct(X)

##__enter__, __exit__

Environment Manager
with obj as var:

##__get__, __set__,

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

Create the object before __init__

The following is an introduction to the use of commonly used operator methods.

Constructor and destructor: __init__ and __del__

## Their main function is to create and recycle objects. When instances When created, the __init__ constructor is called. When the instance object is reclaimed, 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(&#39;Tim&#39;) 
__init__ Tim 
>>> h = &#39;a&#39; 
__del__
Copy after login

Addition and subtraction operations: __add__ and __sub__

Overload these two With this method, you can add the +- operator operation on ordinary objects. The following code demonstrates how to use the +- operator. If the __sub__ method is removed from the code and then the minus operator is called, an error will occur.


>>> 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
Copy after login

String representation of the object: __repr__ and __str__

This Both methods are used to represent the string expression of the object: the print() and str() methods will call the __str__ method, and the print(), str() and repr() methods will call the __repr__ method. As can be seen from 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) 
&#39;__repr__ called&#39; 
>>> str(s) 
&#39;__str__ called&#39;
Copy after login

Index value acquisition and assignment: __getitem__, __setitem__

By implementing these two methods, You can get and assign values ​​to objects in the form such as X[i], and you can also use slicing operations on objects.


>>> 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]
Copy after login

Set and access attributes: __getattr__, __setattr__


We can overload __getattr__ and __setattr_ _ to intercept access to object members. __getattr__ is automatically called when accessing a member that does not exist in the object. The __setattr__ method is used to call when initializing object members, that is, the __setattr__ method is called when setting the item of __dict__. The specific 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()
Copy after login

The running results of the above code are as follows. From the results, it can be seen that __getattr_ will be called when accessing the non-existent variable x _method; when __init__ is called, the assignment operation also calls the __setattr__ method.

__setattr__ 
__setattr__ 
{&#39;a&#39;: 1, &#39;b&#39;: 2} 
__getattr__ 
__setattr__ 
{&#39;a&#39;: 1, &#39;x&#39;: 3, &#39;b&#39;: 2}
Copy after login

Iterator object: __iter__, __next__
## Iteration in Python can be done directly by repeating Load the __getitem__ method to achieve this, see the example below.


>>> 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
Copy after login

Iteration can be achieved through the above method, but it is not the best way. Python's iteration operation will first try to call the __iter__ method, and then try __getitem__. The iterative environment is implemented by using iter to try to find the __iter__ method, which returns an iterator object. If this method is provided, Python will repeatedly call the iterator object's next() method until a StopIteration exception occurs. If __iter__ is not found, Python will try to use the __getitem__ mechanism. Let's look at 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
Copy after login

The running result of the program 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
Copy after login

It can be seen that the implementation After the __iter__ and __next__ methods, the object can be iterated through the for in method, or the object can be iterated through the iter() and next() methods.

Thank you for reading, I hope it can help you, thank you for your support of this site!

The above is the detailed content of Detailed explanation of Python operator overloading example code sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template