__init__
method. This method is automatically called when an object is created. Here’s the syntax for defining a constructor:self
. It initializes the object with default values.
In the example above, the __init__
method initializes the age
attribute with a default value of 22 when the john
object is created.age
and salary
as parameters and initializes the object with those values.__del__
method. It is automatically called when an object is deleted using the del
keyword or when the object goes out of scope.
In the above example, the __del__
method prints a message when the john
object is deleted using the del
keyword.Feature | Constructor | Destructor |
---|---|---|
Purpose | Initialize an object when it is created | Clean up before an object is deleted |
Method Name | __init__ | __del__ |
Invocation | Automatically called when creating an object | Automatically called when deleting an object |
Use Case | Setup object attributes | Release resources like files, databases |