Dunder methods

init, repr, str, cmp, new , del, hash, nonzero, unicode, class operators

  • __init__ The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created.
  • repr() The repr() function returns a printable representation of the given object.
  • The __str__ method in Python represents the class objects as a string – it can be used for classes. The str method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.
  • __cmp__ is no longer used.
  • __mew__ Whenever a class is instantiated __new__ and __init__ methods are called. __new__ method will be called when an object is created and __init__ method will be called to initialize the object.
  • class A(object):
        def __new__(cls):
             print("Creating instance")
             return super(A, cls).__new__(cls)
      
        def __init__(self):
            print("Init is called")
    
    # Creating instance
    # Init is called
  • __hash__()
  • class A(object):
        def __init__(self, a, b, c):
            self._a = a
            self._b = b
            self._c = c
    
        def __eq__(self, othr):
            return (isinstance(othr, type(self))
                    and (self._a, self._b, self._c) ==
                        (othr._a, othr._b, othr._c))
    
        def __hash__(self):
            return hash((self._a, self._b, self._c))
  • Rich comparison methods
  • __lt____gt____le____ge____eq__, and __ne__

    def __lt__(self, other):
       ...
    def __le__(self, other):
       ...
    def __gt__(self, other):
       ...
    def __ge__(self, other):
       ...
    def __eq__(self, other):
       ...
    def __ne__(self, other):
       ...
  • __call__
  • object() is shorthand for object.__call__()

    class Product:
        def __init__(self):
            print("Instance Created")
      
        # Defining __call__ method
        def __call__(self, a, b):
            print(a * b)
      
    # Instance created
    ans = Product()
      
    # __call__ method will be called
    ans(10, 20)
  • __contains__ for i in self:
SuperMade with Super