Code section:
The class Test:
Def __init__ (self, val) :
Self. Val val=
Def __add__ (self, other) :
Print (' add ', the self. Val, other)
Return the self. Val + other
Question part:
1, define operator overloading, there are rules to write it? Define __add__, for example, must be accept two parameters (self, other), it must be return self. Val + other? Whether each operator overloading has specific written rules? Also like the __getitem__ overloading, examples in the book wrote:
The class Test:
Def __getitem__ (self, I) :
Return the self. The data [1]
2, why write? If just want to make a custom class with the function of the iteration is only write def __getitem (self) : it is ok to pass?
3, in defining __add__, also only wrote the symbol "+", my understanding is: how to "add" python itself is packaged, the usefulness of operator overloading is just in order to allow the user to define the class has a "+" operation, at most let you customize the "+" do not know what they do, on the basis of this understanding right, about operator overloading can give a practical point of use?