The Python operator overload details and instance code

  • 2020-05-27 05:57:21
  • OfStack

The Python operator is overloaded

The Python language provides operator overloading to increase the flexibility of the language, which is somewhat similar to and somewhat different from C++. In view of its specificity, today we will discuss 1 Python operator overloading.

The Python language itself provides many magic methods, and its operator overloading is done by overwriting these built-in magic methods. These magic methods all start and end with a double underscore, similar to the form with s 11en__, and python intercepts the operator with this special nomenclature to reload. When Python's built-in operations apply to class objects, Python searches for and calls methods specified in the object to complete the operations.

Class can overload addition and subtraction operations, printing, function calls, indexes and other built-in operations, operator overloading makes our objects behave like built-in objects. Python will call this method automatically when calling the operator, for example, if the class implements the s 18en__ method, this method will be called when the class's object appears in the + operator.

Common operator overload methods

方法名

重载说明

运算符调用方式

__init__

构造函数

对象创建: X = Class(args)

__del__

析构函数

X对象收回

__add__/__sub__

加减运算

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

__or__

运算符|

X|Y, X|=Y

_repr__/__str__

打印/转换

print(X)、repr(X)/str(X)

__call__

函数调用

X(*args, **kwargs)

__getattr__

属性引用

X.undefined

__setattr__

属性赋值

X.any=value

__delattr__

属性删除

del X.any

__getattribute__

属性获取

X.any

__getitem__

索引运算

X[key],X[i:j]

__setitem__

索引赋值

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

__delitem__

索引和分片删除

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

__len__

长度

len(X)

__bool__

布尔测试

bool(X)

__lt__, __gt__, 

__le__, __ge__, 

__eq__, __ne__

特定的比较

依次为X<Y,X>Y,X<=Y,X>=Y, 

X==Y,X!=Y 

注释:(lt: less than, gt: greater than, 

  le: less equal, ge: greater equal, 

  eq: equal, ne: not equal 

__radd__

右侧加法

other+X

__iadd__

实地(增强的)加法

X+=Y(or else __add__)

__iter__, __next__

迭代

I=iter(X), next()

__contains__

成员关系测试

item in X(X为任何可迭代对象)

__index__

整数值

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

__enter__, __exit__

环境管理器

with obj as var:

__get__, __set__, 

__delete__

描述符属性

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

__new__

创建

在__init__之前创建对象

The following section describes the use of common operator methods.

Constructors and destructors: s 30en__ and s 31en__

Their main function is to create and recycle the object, and the build method is called with the creation of the instance. The destructor function is automatically executed when the instance object is recalled.


>>> 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__ 

Add and subtract operations: s 41en__ and s 42en__

Overloading these two methods adds the +- operator operation to normal objects. The following code demonstrates how to use the +- operator. If you remove the method of s 46en__ in the code, it will be wrong to call the minus operator again.


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

The string representation of the object is: s 51en__ and s 52en__

Both of these methods are used to represent the string representations of the object: print(), str() will call the method of s 58en__, print(), str() and repr() will call the method of s 62en__. As can be seen from the following example, when both methods are simultaneously defined, Python will give priority to searching and calling the s 64en__ 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 values and assignments: s 68en__, s 69en__

By implementing these two methods, you can evaluate and assign objects in a form such as X[i], or you can slice them.


>>> 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: s 79en__, s 80en__

We can block access to object members by reloading s 84en__ and s 85en__. S 86en__ will be automatically invoked by accessing non-existing members of the object. The method is used to call while initializing the object member, i.e., with the setting of item of s 88en__, s 90en__ method will be called. Specific examples are 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 results of the above code are shown as follows. It can be seen from the results that the method is called while accessing the non-existing variable x. The assignment operation will also call the method of s 98en__ when s 97en__ is called.


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

Iterator object: s 102en__, s 103en__

The iteration in Python can be accomplished directly with the method of overloaded s 108en__, 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 

Iteration can be achieved with the above approach, but it is not the best way. The iteration operation of Python will first try to call the method of s 114en__, then s 115en__. The iterative environment is implemented by iter trying to find the method of s 117en__, which returns one iterator object. If this method is already provided, Python will repeatedly call the next() method of the iterator object until an StopIteration exception occurs. If no s are found, Python will try to use the s 123en__ mechanism. Let's take a 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 

The results of the program are 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 implementing the methods of s 131en__ and s 132en__, the object can be iterated by for in, and by iter() and next().

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


Related articles: