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

Detailed explanation of Python operator overloading example code sharing

Mar 10, 2017 am 09:07 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles