Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
numpy.promote_types() function – 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.

Method Operation
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 :

Method Operation
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.

Method Operation
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.

Method Operation
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 :

Method Description
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
numpy.promote_types() function – Python
author
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
  • Format a Number Width in Python
    Formatting numbers to a fixed width is a common requirement in various programming tasks, especially when dealing with data presentation or storage. By understanding these techniques, developers can ensure consistent and visually appealing formatting of numerical data in their Python. Format a Numbe
    3 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
  • Data type Object (dtype) in NumPy Python
    Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us about the layout of the array. This means it gives us information about: Type of the data (integer, float, Python object, etc.)Size of the data (number of bytes)The byte order of the data (little-endia
    3 min read
  • type and isinstance in Python
    In this article, we will cover about type() and isinstance() function in Python, and what are the differences between type() and isinstance(). What is type in Python? Python has a built-in method called type which generally comes in handy while figuring out the type of the variable used in the progr
    5 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 occup
    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
  • Type Hints in Python
    Type hints are a feature in Python that allow developers to annotate their code with expected types for variables and function arguments. This helps to improve code readability and provides an opportunity to catch errors before runtime using type checkers like mypy. Using Type Hints in Python1. Vari
    3 min read
  • numpy.common_type() function – Python
    numpy.common_type() function return a scalar type which is common to the input arrays. Syntax : numpy.common_type(arrays) Parameters : array1, array2, .... : [ndarrays] Input arrays. Return : [dtype] Return the data type which is common to the input arrays. Code #1 : # Python program explaining # nu
    1 min read
  • numpy.typename() function – Python
    numpy.typename() function return a description for the given data type code. Syntax : numpy.typename(char) Parameters : char : [str] Data type code. Return : [str] Description of the input data type code. Code #1 : # Python program explaining # numpy.typename() function # importing numpy as geek imp
    2 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