Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
No edit summary
m Python: <source lang="pycon">
Line 525:
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.)
 
<source lang="pythonpycon">
>>> class ExampleClass(object):
... def __new__(cls, value):
... print("Creating new instance...")
... # Call the superclass constructor to create the instance.
... instance = super(ExampleClass, cls).__new__(cls)
... return instance
... def __init__(self, value):
... print("Initialising instance...")
... self.payload = value
>>> exampleInstance = ExampleClass(42)
 
Creating new instance...
exampleInstance = ExampleClass(42)
# prints "Creating new instance..." followed by "Initialising instance..."
>>> print(exampleInstance.payload)
 
42
print(exampleInstance.payload)
# prints 42
</source>