042 Magic methods: Arithmetic operations

Source: Internet
Author: User
Tags bitwise integer division

Since python2.2, the classes and types have been unified,
The practice is to convert int (), float (), str (), list (), tuple () to factory function
Factory functions: Is an object that, when you call them, is actually creating a corresponding instance object
such as: >>>a = Int (' 123 ')
>>>b = Int (' 456 ')
>>>a + b
579
A and B are factory functions (class objects), an instance object of int
The __add__ Magic function is automatically called when objects A and B are added together.

The Magic function corresponding to the arithmetic operation:
__ADD__ (Self,other) defines the behavior of the addition: +
__SUB__ (Self,other) defines the behavior of subtraction:-
__MUL__ (Self,other) defines the behavior of multiplication: *
__TRUEDIV__ (Self,other) defines the behavior of true division:/
__FLOORDIV__ (Self,other) defines the behavior of integer division://
__MOD__ (Self,other) defines the behavior of the modulo operation:%
__DIVMOD__ (Self,other) defines behavior when called by the Divmod ()
__pow__ (Self,other[,modulo]) defines the behavior of a power () call or a * * operation
__LSHIFT__ (Self,other) defines the behavior of the bitwise left SHIFT:<<
__RSHIFT__ (Self,other) defines the behavior of the bitwise right SHIFT:>>
__ADD__ (Self,other) defines the behavior of the addition:&
__XOR__ (Self,other) defines the behavior of the addition: ^
__OR__ (Self,other) defines the behavior of the addition: |


For example:>>> class new_int (int):
... def __add__ (self,other):
... return int.__sub__ (self,other)
... def __sub__ (self,other):
... return int.__add__ (self,other)
...
>>> a = New_int (3)
>>> B = New_int (5)
>>> a+b
-2
>>> A-B
8
Is it possible to return without calling int's Magic method?
>>> class New_int (int):
... def __add__ (self,other):
... return self + other
... def __sub__ (self,other):
... return Self-other
...
>>> a = New_int (3)
>>> B = New_int (5)
>>> A + B will be infinite recursion, then exit
File "<stdin>", line 3, in __add__
............
File "<stdin>", line 3, in __add__
Runtimeerror:maximum recursion depth exceeded while calling a Python object

Can be modified:
>>> class Try_int (int):
... def __add__ (self,other):
... return int (self) + int (other)
... def __sub__ (self,other):
... return int (self)-int (other)
...
>>> a = Try_int (3)
>>> B = Try_int (5)
>>> A + b
>>>8


Practice:
1. In Python, two strings can be added automatically stitching, but two string subtraction throws an exception
Now define a NSTR class that supports:-A: Remove all B substrings from A
such as:>>> class Nstr (str):
... def __sub__ (self,other):
... return self.replace (Other, ')
...
>>> a = Nstr ("123aaa")
>>> B = Nstr ("a")
>>> A-B
' 123 '
Heavy __sub__ Magic method can be

2. The shift operator applies the binary operand, defines a new class nstr, and also supports the operation of the operator
such as:>>> class Nstr (str):
... def __lshift__ (self,other):
... return Self[other:] + self[:other]
... def __rshift__ (self,other):
... return self[:-other] + Self[-other:]
...
>>> a = Nstr (' I love you! ')
>>> a << 3
' Ove you! I l '
>>> a >> 3
' I Love you! '

3. Define a class nstr that computes the sum of the ASCII code of all the strings of an object when the instance object of the class occurs +-*/.
>>> class Nstr (int):
... def __new__ (cls,arg=0):
... if Isinstance (ARG,STR):
... Total = 0
... for each in ARG:
... Total + = ord (each)
... arg = Total
... return int.__new__ (CLS,ARG)
...
>>> a = nstr (' I ')
>>> B = nstr (' Love ')
>>> C = nstr (' You ')
>>> A + B + C
636

042 Magic methods: Arithmetic operations

Contact Us

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.