Wednesday, June 5, 2019

Magic Methods in Python With Examples

In Python there are predefined special methods that follow the convention of having method names suffixed and prefixed with double underscores for example __init__(). These special methods are also known as magic methods in Python and also as Dunders (Double UNDERscores).


Python magic methods

These built in methods in Python are known as magic methods as these methods are called automatically to execute the functionality as required by the performed action.

For example when you create an object of a class magic methods __new__() and __init__() are called internally;

  • __new__() is called to create a new instance of class.
  • __init__() is called to initialize the created object.

Another example of magic method is when you add two numbers i.e. a + b, internally __add__() method is called to execute that functionality. More specifically when you write a + b magic method is called internally as a.__add__(b).

Usage of magic methods in Python

Magic methods can be overridden in your class to change the default functionality and fashion these methods as per your custom object needs.

Using magic methods you can do operator overloading in Python. By overriding the corresponding magic method a class can define its own behavior with respect to language operators. For example magic method for multiplication operator (*) is __mul__() so you can overload * operator by overriding __mul__() method in your class.

Available magic methods in Python

There are many magic methods in Python which are called automatically when object is initialized, when object is destroyed, for binary operators, for unary operators, for compound assignment operators, for representing object as string and many mores. We’ll see some of the most used magic methods in this section along with examples of those magic methods.

Magic methods for basic object customization


Magic Method Description
__new__(cls[, ... ])Called to create a new instance of class cls.
__init__(self [, ... ])Called to initialize the object after it is created. This method is called after the instance has been created (by __new__()), but before it is returned to the caller.
__del__(self )Called when the instance is about to be destroyed.

__init__() and __new__() method Python example

In reality most probably __init__() will be the most used magic method for you where as you will explicitly use __new__() method very rarely.

class Person:
  def __new__(cls, x, y):
    print('__new__ called to create object')
    # return created instance
    return super().__new__(cls)
  def __init__(self, name, salary):
    print('__init__ called for object initialization')
    self.name = name
    self.salary = salary

obj1 = Person('John', 4500)
obj2 = Person('Natasha', 6000)

Output

__new__ called to create object
__init__ called for object initialization
__new__ called to create object
__init__ called for object initialization

Magic methods for string representation of an object


Magic Method Description
__repr__(self )Called by the repr() built-in function to compute the “official” string representation of an object.
__str__(self )Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object.
__bytes__(self )Called by bytes to compute a byte-string representation of an object. This should return a bytes object.
__format__(self, format_spec)Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object.

__str__() magic method Python example

class Person:
  def __init__(self, name, salary):
    print('__init__ called for object initialization')
    self.name = name
    self.salary = salary
  def __str__(self):
    return "Name - " + self.name + " Salary - " + str(self.salary)

obj1 = Person('John', 4500)
obj2 = Person('Natasha', 6000)
print(obj1)
print(obj2)

Output

__init__ called for object initialization
__init__ called for object initialization
Name - John Salary - 4500
Name - Natasha Salary – 6000

Magic methods for arithmetic operators


Operator Magic Method Description
+__add__(self, other)Additive operator
-__sub__(self, other)Subtraction operator
*__mul__(self, other)Multiplication operator
/__truediv__(self, other)Division with fractional result
%__mod__(self, other)Remainder operator
//__floordiv__(self, other)Division with integer result, discarding any fractional part
**__pow__(self, other)Return a to the power b, for a and b numbers.
@__matmul__(self, other)Matrix Multiplication. Available from version 3.5

Overloading ‘*’ operator in Python

class Point:
  def __init__(self, x):
    self.x = x
  #overriding magic method
  def __mul__(self, other):
    return self.x * other.x

p1 = Point(12)
p2 = Point(5)
print(p1*p2)

Output

60

Magic methods for Comparison operators


Operator Magic Method Description
<__lt__(self, other)less than
<=__le__(self, other)less than or equal to
==__eq__(self, other)equal to
!=__ne__(self, other)not equal to
>__gt__(self, other)greater than
>=__ge___(self, other)greater than or equal to

Magic methods for compound assignment operators


Operator Magic Method Description
+=__iadd__(self, other)Addition assignment
–=__isub__(self, other)Subtraction assignment
*=__imul__(self, other)Multiplication assignment
/=__itruediv__(self, other)Division assignment
%=__imod__(self, other)Modulus assignment
//=__ifloordiv__(self, other)Division with integer result, discarding any fractional part
**=__ipow__(self, other)Return a to the power b, for a and b numbers.
@=__imatmul__(self, other)Matrix Multiplication. Available from version 3.5

Magic methods for unary operators


Operator Magic Method Description
+__pos__(self, other)Unary plus operator; indicates positive value
-__neg__(self, other)Unary minus operator; negates an expression
~__invert__(self, other)Returns the bitwise inverse of the number

Overloading comparison operator (>) in Python

class Person:
  def __init__(self, name, salary):
    self.name = name
    self.salary = salary
  #overriding magic method
  def __gt__(self, other):
    return self.salary > other.salary

obj1 = Person('John', 4500)
obj2 = Person('Natasha', 6000)
print(obj1.name, 'earns more than', obj2.name, '-', obj1 > obj2)

Output

John earns more than Natasha - False

Magic methods for container types

If you want your object to emulate container types (List, tuples) then you can override one of the following magic methods for container types.

Magic Method Description
__len__(self )Called to implement the built-in function len() which returns the length of the container.
__getitem__(self, key)To implement behavior for accessing an item using self[key] notation.
__setitem__(self, key, value)To implement behavior to set an item value using self[key]=value notation.
__delitem__(self, key)To implement behavior to delete an item using del self[key] notation.
__iter__(self )This method is called when an iterator is required for a container.
__reversed__(self )To implement reverse iteration.
__contains__(self, item)To implement membership test operators. Should return true if item is in self, false otherwise.

Overloading len magic method in Python

In the following example class overrides __len__() magic method to return the number of transactions using Account object.

class Account:
  def __init__(self, name, acct_num):
    self.name = name
    self.acct_num = acct_num
    #list to add transactions
    self.transactions = []

  def withdraw(self, amount):
    print('Withdrawing amount for ', self.acct_num)
    self.transactions.append(amount)

  def deposit(self, amount):
    print('Depositing amount for ', self.acct_num)
    self.transactions.append(amount)
        
  #oveririding len magic method
  def __len__(self):
    return len(self.transactions)

pa = Account('Ian', 1001)
pa.withdraw(100)
pa.deposit(500)
pa.withdraw(50)
# Using len method with custom object
print('Total Number of Transactions in account- ', len(pa))

Output

Withdrawing amount for  1001
Depositing amount for  1001
Withdrawing amount for  1001
Total Number of Transactions in account-  3

That's all for this topic Magic Methods in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Passing Object of The Class as Parameter in Python
  2. Abstract Class in Python
  3. Global Keyword in Python With Examples
  4. Multiple Inheritance in Python
  5. Namespace And Variable Scope in Python

You may also like-

  1. Python String split() Method
  2. Python assert Statement
  3. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  4. Convert String to int in Python
  5. LinkedHashMap in Java
  6. Object Creation Using new Operator in Java
  7. Benefits, Disadvantages And Limitations of Autowiring in Spring
  8. Data Locality in Hadoop

No comments:

Post a Comment