Dunder or magic methods in python

PythonProgrammingServer Side Programming

magic methods that allow us to do some pretty neat tricks in object oriented programming. These methods are identified by a two underscores (__) used as prefix and suffix. As example, function as interceptors that are automatically called when certain conditions are met.

In python __repr__ is a built-in function used to compute the "official" string representation of an object, while __str__ is a built-in function that computes the "informal" string representations of an object.

Example Code

Live Demo

class String:
   # magic method to initiate object
   def __init__(self, string):
      self.string = string
# Driver Code
if __name__ == '__main__':
   # object creation
   my_string = String('Python')
   # print object location
   print(my_string)

Output

<__main__.String object at 0x000000BF0D411908>

Example Code

Live Demo

class String:
   # magic method to initiate object
   def __init__(self, string):
      self.string = string
   # print our string object
   def __repr__(self):
      return 'Object: {}'.format(self.string)
# Driver Code
if __name__ == '__main__':
   # object creation
   my_string = String('Python')
   # print object location
   print(my_string)

Output

Object: Python

We are trying to add a string to it.

Example Code

Live Demo

class String:
   # magic method to initiate object
   def __init__(self, string):
      self.string = string
   # print our string object
   def __repr__(self):
      return 'Object: {}'.format(self.string)
# Driver Code
if __name__ == '__main__':
   # object creation
   my_string = String('Python')
   # concatenate String object and a string
   print(my_string + ' Program')

Output

TypeError: unsupported operand type(s) for +: 'String' and 'str'

Now add __add__ method to String class

Example Code

class String:
   # magic method to initiate object
   def __init__(self, string):
      self.string = string
   # print our string object
   def __repr__(self):
      return 'Object: {}'.format(self.string)
   def __add__(self, other):
      return self.string + other
# Driver Code
if __name__ == '__main__':
   # object creation
   my_string = String('Hello')
   # concatenate String object and a string
   print(my_string +' Python')

Output

Hello Python
raja
Updated on 30-Jul-2019 22:30:23

Advertisements