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!