043 Magic Methods: arithmetic Operations 2

Source: Internet
Author: User

Inverse operation:
Called when the left operand does not support a response operation
such as: Object (A+B), if the A object has a __add__ method, the __radd__ of the B object is not called
The __radd__ method of B is called only if the __add__ method of the A object is not implemented or does not support the corresponding operation.

such as:>>> class Nint (int):
... return int.__sub__ (self,other)
...
>>> a = Nint (5)
>>> B = Nint (3)
>>> A + b
2
>>> 1 + B When 1 did not find the response to the action to press B, so it was executed B's
2
such as:>>> class Nint (int):
... def __rsub__ (Self,other)
... return int.__sub__ (self,other)
...
>>> a = Nint (5)
>>> 3-a shouldn't be-2? Why is it?
2
such as:>>> class Nint (int):
... def __rsub__ (self,other):
... return int.__sub__ (other,self) Just change the position of the parameter here, the result is different
...
>>> a = Nint (5)
>>> 3-a
-2

Unary operators:
_neg_ (self) defines the behavior of a positive sign: +x
_pos_ (self) defines the behavior of the minus sign:-X
_abs_ (self) defines the behavior when being called by ABS ()
_invert_ (self) defines the bitwise negation behavior: ~x

Practice:
1. Define a class that automatically determines how many parameters are passed in when the class is instantiated and displays
such as:>>> class C:
... def __init__ (Self,*args):
... if not args:
... print ("WU")
.. else:
... print ("%d,:"% len (args)),
... for each in args:
.. print (each),
...

043 Magic Methods: arithmetic Operations 2

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• Sales Support

1 on 1 presale consultation

• After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.