Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Emulating Numeric types in Python
Next article icon

Emulating Numeric types in Python

Last Updated : 27 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The following are the functions which can be defined to emulate numeric type objects. 

Methods to implement Binary operations on same type of objects :

These functions will make no change in the calling object rather they will return a new numeric object of same type after performing certain operation on the calling object. Following are the methods to implement arithmetic binary operations.

MethodOperation
object.__add__(self, other)+ (Addition)
object.__sub__(self, other)- (Subtraction)
object.__mul__(self, other)* (Multiplication)
object.__matmul__(self, other)@ (Matrix multiplication)
object.__truediv__(self, other)/ (True division)
object.__floordiv__(self, other)// (Floor division)
object.__mod__(self, other)% (Modulus or remainder)
object.__divmod__(self, other)divmod()
object.__pow__(self, other[, modulo])** (power)
object.__lshift__(self, other)<< (Bit wise left shift)
object.__rshift__(self, other)>> (Bit wise right shift)
object.__and__(self, other)& (Bit wise AND operation)
object.__xor__(self, other)^ (Exclusive OR operation)
object.__or__(self, other)| (Bit wise OR operation)

The __pow__() is defined to accept a third optional argument so as to support the ternary version of pow() function. Also if any of above method does not support the operation it should return NotImplemented .

Methods to implement Binary operations on different type of objects :

If type of object at left (callable object) is different than following methods can be used to perform arithmetic binary operations :

MethodOperation
object.__radd__(self, other)+ (Addition)
object.__rsub__(self, other)- (Subtraction)
object.__rmul__(self, other)* (Multiplication)
object.__rmatmul__(self, other)@ (Matrix multiplication)
object.__rtruediv__(self, other)/ (True division)
object.__rfloordiv__(self, other)// (Floor division)
object.__rmod__(self, other)% (Modulus or remainder)
object.__rdivmod__(self, other)divmod()
object.__rpow__(self, other[, modulo])** (pow() or power of number)
object.__rlshift__(self, other)<< (Bit wise left shift)
object.__rrshift__(self, other)>> (Bit wise right shift)
object.__rand__(self, other)& (Bit wise AND operation)
object.__rxor__(self, other)^ (Exclusive OR operation)
object.__ror__(self, other)| (Bit wise OR operation)

For example, if in a.__sub__(b), a is not of numeric type as of b then this method will return NotImplemented, then to perform a - b we will call a.__rsub__(b).

Methods to implement arithmetic assignment operations :

These methods are used to implement the arithmetic assignment operations. They will not return a new object rather they will assign the new value in calling object itself. Like x.__imul__(y) will be performed as x = x * y. Following are the corresponding operations to each method.

MethodOperation
object.__iadd__(self, other)+= (Addition assignment)
object.__isub__(self, other)-= (Subtraction assignment)
object.__imul__(self, other)*= (Multiplication assignment)
object.__imatmul__(self, other)@= (Matrix multiplication assignment)
object.__itruediv__(self, other)/= (True division assignment)
object.__ifloordiv__(self, other)//= (Floor division assignment)
object.__imod__(self, other)%= (Modulus or remainder assignment)
object.__ipow__(self, other[, modulo])**= (power of number assignment)
object.__ilshift__(self, other)<<= (Bit wise left shift assignment)
object.__irshift__(self, other)>>= (Bit wise right shift assignment)
object.__iand__(self, other)&= (Bit wise AND operation assignment)
object.__ixor__(self, other) ^= (Exclusive OR operation assignment)
object.__ior__(self, other)|= (Bit wise OR operation assignment)

Methods to implement unary arithmetic operations :

Following are the methods to implement unary arithmetic operations like, negative of a number, inverse of a number etc.

MethodOperation
object.__neg__(self)- (unary minus)
object.__pos__(self)+ (unary plus)
object.__abs__(self)abs() in-built function
object.__invert__(self)~ (complement of a number)

Some other important methods :

MethodDescription
object.__index__(self)

Called to implement operator.index() function, also used to convert a numeric type object to integer type,  

or we can say if __int__(), __float__() or __complex__() is not defined then int(), float() and complex() falls 

under __index__().

object.__round__(self, ndigits)

To implement the round() function, the second optional argument tells up to how many decimal places 

we want to round the numeric value.

object.__trunc__(self)To implement trunc() function.
object.__floor__(self)To implement floor() function.
object.__ceil__(self)To implement ceil() function.

Next Article
Emulating Numeric types in Python

A

amit_mangal_
Improve
Article Tags :
  • Python
  • Python-Miscellaneous
Practice Tags :
  • python

Similar Reads

    type() function in Python
    The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
    5 min read
    numpy.promote_types() function – Python
    numpy.promote_types() function is a symmetric function which returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 may be safely cast. The returned data type is always in native byte order. Syntax : numpy.promote_types(type1, type2) Parameters : type1 :
    1 min read
    Number System in Python
    The arithmetic value that is used for representing the quantity and used in making calculations is defined as NUMBERS. The writing system for denoting numbers logically using digits or symbols is defined as a Number system. Number System is a system that defines numbers in different ways to represen
    6 min read
    Float type and its methods in python
    A float (floating-point number) is a data type used to represent real numbers with a fractional component. It is commonly used to store decimal values and perform mathematical calculations that require precision.Characteristics of Float TypeFloats support decimal and exponential notation.They occupy
    5 min read
    numpy.maximum_sctype() function – Python
    numpy.maximum_sctype() function return the scalar type of highest precision of the same kind as the input. Syntax : numpy.maximum_sctype(t) Parameters : t : [dtype or dtype specifier] The input data type. This can be a dtype object or an object that is convertible to a dtype. Return : [dtype] The hi
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences