In python object-oriented programming there is no such concept of constructor. But there is an alternative of constructor which is called. _init__() method. But we cant say it constructor because the instance of the class is initialized before. _init__() method is called. This method is used to initialize the value of data immediately after instance is created.
This method makes the work easy we don’t have to set the values before running the method values are initialized at creating instance. We can also make non-parameterized constructor as follows”
The output will be the same. Similarly, we can make default values in constructor too just we saw in the function module.
Destructor in Python:
Unlike constructor which initialize the values destructor destroy the instance of the class. It destroys the object and its data member. Following example will clear the concept of destructor.
In the above example we make a instance of a class and initialize the name. Than print the name and destroy the object. After that when we again accessed the object python interpreter will generate an error no obj is defined:
That trackback show that after destroying the object it will removed from the memory.
Public Data Member:
Public data members are the members that can be accessed outside the class too. In python there is no such keyword for public data member. The data member that we initialized in the above examples are public data member. It can be accessed from inside as well as outside of the class.
Here name is public data member
Protected Data members:
Unlike public data members protected data members can only be accessed by the class and the class that inherits it. It cannot be accessed from outside of the class that is not inherited. To make a protected data member we have to give underscore sign before the variable name. Following is the example of protected data members:
Here the _name is protected data members.
Private Data Members:
Private data member cannot be accessed by the class itself. It cannot be accessed from outside the class nor from the inherited class. It is private from all and cannot be seen. To make a variable private we must write “__” (two times underscore) before the variable name. Following is the example of private data members:
Here the name is private data member.