April 2019
Intermediate to advanced
646 pages
16h 48m
English
The special method __new__() is a static method that's responsible for creating class instances. It is special-cased, so there is no need to declare it as static using the staticmethod decorator. This __new__(cls, [,...]) method is called prior to the __init__() initialization method. Typically, the implementation of overridden __new__() invokes its superclass version using super().__new__() with suitable arguments and modifies the instance before returning it.
The following is an example class with the overridden __new__() method implementation in order to count the number of class instances:
class InstanceCountingClass: instances_created = 0 def __new__(cls, *args, **kwargs): ...