


Detailed explanation of Python operator overloading example code sharing
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
##Method name | Overloading description | Operator calling method |
__init__ | Constructor | Object creation: X = Class(args) |
__del__ | Destructor | X object is recovered |
Addition and subtraction operations | X+Y, X+=Y/X-Y, X-=Y |
|
Operator| | X|Y, X|=Y | |
Print/Convert | print(X) , repr(X)/str(X) | |
Function call | X(*args, **kwargs) | |
##Attribute reference |
X.undefined |
__setattr__ |
Attribute assignment |
X.any=value |
__delattr__ |
Attribute deletion |
del | X.any|
Index operation | X[key],X[i:j] | |
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__, |
__eq__, __ne__ | Specific comparison | in sequence For X |
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( ) | ##__contains__ | Membership Test |
item in X (X is any iterable object) |
__index__ | Integer value |
hex(X), bin(X), oct(X) |
##__enter__, __exit__ | Environment Manager |
with obj as var: | ##__get__, __set__, | __delete__Descriptor attribute |
X.attr, X.attr=value, del X.attr |
__new__ | Create |
Create the object before __init__ |
The following is an introduction to the use of commonly used operator methods. Constructor and destructor: __init__ and __del__ >>> 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__ Copy after login Addition and subtraction operations: __add__ and __sub__ >>> 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__ >>> 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' Copy after login Index value acquisition and assignment: __getitem__, __setitem__ >>> 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 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 __setattr__ __setattr__ {'a': 1, 'b': 2} __getattr__ __setattr__ {'a': 1, 'x': 3, 'b': 2} Copy after login Iterator object: __iter__, __next__ >>> 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

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 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? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Using python in Linux terminal...

Fastapi ...

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)...
