Python Object Creation

To create an object, define dunder method __new__ instead of init#. The reason is __new__ happen earlier than __init__, and it can alter both mutable and immutable object by creating a new instance of the same class or type compare to __init__ which can’t change the immutable object. Furthermore, __new__ allows cheaper object creation by detecting whether the object has already exists. If it is, there is no need to create another instance of it, __new__ will simply return that object. Such implementation is shown as below:

Links to this page
  • Python Object Initialisation

    We can initialise an existing class object by using the dunder method __init__. However, with this method, we can’t alter immutable object such as tuple in the class object since it is already created before we could initialise it. The alternative for it is to use another dunder method, #new.

#python #resource #oop