CLASSES AND OBJECTS
Constructor,
Destructor
CONSTRUCTOR
• Constructors are generally used for instantiating an
object.
• The task of constructors is to initialize(assign values) to
the data members of the class when an object of the
class is created.
• In Python the __init__() method is called the constructor
and is always called when an object is created.
FEATURES OF PYTHON CONSTRUCTORS
• In Python, a Constructor begins with double underscore
(_) and is always named as __init__().
• In python Constructors, arguments can also be passed.
• In Python, every class must necessarily have a
Constructor.
• If there is a Python class without a Constructor, a default
Constructor is automatically created without any
arguments and parameters.
SYNTAX OF CONSTRUCTOR DECLARATION :
def __init__(self):
# body of the constructor
TYPES OF CONSTRUCTORS
• Parameterized Constructor
• Non- Parameterized Constructor (Default)
TYPES
• Default constructor: The default constructor is a simple
constructor which doesn’t accept any arguments. Its definition has
only one argument which is a reference to the instance being
constructed.
• Parameterized constructor: constructor with parameters is
known as parameterized constructor. The parameterized
constructor takes its first argument as a reference to the instance
being constructed known as self and the rest of the arguments are
provided by the programmer.
DESTRUCTORS
• Destructors are called when an object gets destroyed. In Python,
destructors are not needed as much as in C++ because Python
has a garbage collector that handles memory management
automatically.
• The __del__() method is a known as a destructor method in
Python. It is called when all references to the object have been
deleted i.e when an object is garbage collected.
SYNTAX
def __del__(self):
# body of destructor
THANKS