A
A
Andrey Gorbik2018-10-31 18:03:42
Python
Andrey Gorbik, 2018-10-31 18:03:42

How does __new__ work in the above code?

I saw an example of Singleton'a, I do not quite understand the specified line of code.

class Singleton:
  instance = None

  def __new__(cls):
    if cls.instance is None:
      cls.instance = super().__new__(cls) # <-- данная строчка вызывает проблемы
    return cls.instance

a = Singleton()
b = Singleton()
print(a is b) # True

The super() function refers to the parent of the class, because to object, as far as I understand.
I don't understand why the __new__ magic method of the parent class is called to create a new class instance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bobsans, 2018-10-31
@and_gorbik

__new__ from object would have been called anyway. This is the instantiation of an object. It's just that in this example, we override it and call super() to execute the code from the parent's __new__ method.
In the example, cls is passed to __new__ . cls is the type of object to be created.
The same can be done like this:

def __new__(cls):
    if cls.instance is None:
        cls.instance = object.__new__(cls)
    return cls.instance

Or like this:
class ClassA:
   pass

instance = object.__new__(ClassA) # <ClassA object at 0x0....>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question