python - operator overloading

1. Function: Intercept built-in operations (+, -, *, / etc.) within the class method. When an instance of the class appears in the built-in operation, python automatically calls the overloaded method

eg:

class Number:

def __init__(self,start):#overload constructor

        self.data = start

def __sub__(self,other):// overloaded subtraction

return Number(self.data - other)

>>>from number import Number

>>>X = NUmber(5)

>>>Y = X - 2//Call Number's __sub__

>>>Y.data:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325940971&siteId=291194637