Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
Line 545:
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.)
 
<syntaxhighlight lang="pyconpython">
>>> class ExampleClass:
... def __new__(cls: type, value: int) -> 'ExampleClass':
... print("Creating new instance...")
... # Call the superclass constructor to create the instance.
... instance: 'ExampleClass' = super(ExampleClass, cls).__new__(cls)
... return instance
 
... def __init__(self, value: int) -> None:
... print("Initialising instance...")
... self.payload: int = value
>>> exampleInstance = ExampleClass(42)
 
if __name__ == "__main__":
>>> exampleInstance: ExampleClass = ExampleClass(42)
>>> print(exampleInstance.payload)
</syntaxhighlight>
 
This prints:
<pre>
Creating new instance...
Initialising instance...
>>> print(exampleInstance.payload)
42
</pre>
</syntaxhighlight>
 
Classes normally act as [[Factory (object-oriented programming)|factories]] for new instances of themselves, that is, a class is a callable object (like a function), with the call being the constructor, and calling the class returns an instance of that class. However the <code>__new__</code> method is permitted to return something other than an instance of the class for specialised purposes. In that case, the <code>__init__</code> is not invoked.<ref name="auto"/>