How To Use Python __new__ Method Example

In Python, the __new__ method is similar to the __init__ method, but if both exist, __new__ method executes first. In the base class object, __new__ is defined as a static method and needs to pass a parameter cls. cls represent the classe that need to be instantiated, and this parameter is provided automatically by python parser at instantiation time.

In Python, init() method is responsible for instantiating the class instance, and before init() is called, new() decides whether to use the init() method or not, because new() method can call other class constructors or simply return other objects as instances of this class.

So __new__ method has below characters.

  1. The __new__() method is called when the class is ready to instantiate itself.
  2. The __new__() method is always a static method of the class, even if no static method decorator is added.

1. How To Use __new__ Method Example.

  1. Open a terminal and run command $ python3 to go to python interactive environment console.
    :~$ python3
    Python 3.7.1 (default, Dec 14 2018, 19:28:38) 
    [GCC 7.3.0] :: Anaconda, Inc. on linux
    Type "help", "copyright", "credits" or "license" for more information.
    
  2. First define a class Employee, it has two instance variable name and salary.
    >>> class Employee(object):
    ...   
    ...     def __init__(self, name, salary):
    ...         self.name = name
    ...         self.salary = salary
    ...      
    ...     def __new__(cls, name, salary):
    ...         if 0 < salary < 10000:
    ...             return object.__new__(cls)
    ...         else:
    ...             return None
    ...   
    ...     def __str__(self):
    ...         return '{0}({1})'.format(self.__class__.__name__, self.__dict__)
    
  3. Now create two Employee instance and print out their string representation value.
    >>> emp_tom = Employee('Tom', 8000)
    >>> emp_tom
    <__main__.Employee object at 0x7f2c69811278>
    >>> print(emp_tom)
    Employee({'name': 'Tom', 'salary': 8000})
    >>> 
    >>> 
    >>> emp_richard = Employee('Richard', 20000)
    >>> print(emp_richard)
    None
    

2. Python 3 And Python 2 Use _new_ Differently.

2.1 Use __new__ Method In Python 2.

Please note that the __new__ method is only supported in python version 2.7 or greater.

>>> class Employee(object):
...     def __new__(cls,*args, **kwargs):

...         if not hasattr(cls,'_inst'):

...             print(cls)

...             cls._inst = super(Employee, cls).__new__(cls,*args,**kwargs)

...         return cls._inst

... 

>>> obj = Employee()

<class '__main__.Employee'>

>>> print(obj)

<__main__.Employee object at 0x7f2c698113c8>

2.2 Use __new__ Method In Python 3.

class Employee(object):

    def __new__(cls,*args, **kwargs):

        if not hasattr(cls,'_inst'):

            print(cls)

            cls._inst = super(Employee, cls).__new__(cls)

            # if Python3 is written the same way as Python2 like below, it will throw error "TypeError: object() takes no parameters"

            # cls._inst = super(Employee, cls).__new__(cls, *args,**kwargs)

        return cls._inst