Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
__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
class ClassA:
pass
instance = object.__new__(ClassA) # <ClassA object at 0x0....>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question