:PROPERTIES:
:ID:       aaf77222-82d2-492c-bf5f-2dd47659b1be
:mtime:    20220519210820
:ctime:    20220519082710
:END:
#+title: La méthode __new__

* Synthaxe
#+BEGIN_SRC python
object.__new__(cls, *args, **kwargs)
#+END_SRC
La méthode ~object.__new__~ :
 * Crée les instances d'une classe (constructeur),
 * Est appelée avant ~object.__init__~,
 * Retourne une nouvelle instance ou une référence à une précedente (classes /singleton/).

* Exemples
** Utilisation classique
#+BEGIN_SRC python :results output
class B:

    def __new__(cls, *args, **kwargs):
        print("__new__ running", cls, args, kwargs)
        return super().__new__(cls)

    def __init__(self, *args, **kwargs):
        print("__init__ running", self, args, kwargs)
        return super().__init__(*args, **kwargs)

for i in range(2):
    B()
#+END_SRC
#+RESULTS:
: __new__ running <class '__main__.B'> () {}
: __init__ running <__main__.B object at 0x7f78f614c040> () {}
: __new__ running <class '__main__.B'> () {}
: __init__ running <__main__.B object at 0x7f78f614c040> () {}

** Singleton /design pattern/
#+BEGIN_SRC python :results output
class SingletonClass:     

    _instance = None
    
    def __new__(cls, *args, **kwargs):   
        print("__new__ running", cls, args, kwargs)    
        if cls._instance is None: # Checking if an instance of this class exists            
            cls._instance = super().__new__(cls, *args, **kwargs) # Creating a new instace           
        return cls._instance # Returing the instance 

for i in range(2):
    print(f'{id(SingletonClass())=}')

 #+END_SRC
#+RESULTS:
: __new__ running <class '__main__.SingletonClass'> () {}
: id(SingletonClass())=140699167274272
: __new__ running <class '__main__.SingletonClass'> () {}
: id(SingletonClass())=140699167274272

* Références
 * [[https://python.plainenglish.io/advanced-python-classes-objects-and-mro-423bb01521fb][Advanced Python classes objects and MRO - Medium]]
