Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance members of the class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in Python. It is used to create an object.
Constructors can be of two types.
- Parameterized Constructor
- Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also verify that there are enough resources for the object to perform any start-up task.
Counting the number of objects of a class
The constructor is called automatically when we create the object of the class.
The non-parameterized
The non-parameterized constructor uses when we do not want to manipulate the value or the constructor that has only self as an argument.
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self.
Python Default Constructor
When we do not include the constructor in the class or forget to declare it, then that becomes the default constructor. It does not perform any task but initializes the objects.
|
SN |
Function |
Description |
|
1 |
getattr(obj,name,default) |
It is used to access the attribute of the object. |
|
2 |
setattr(obj,
name,value) |
It is
used to set a particular value to the specific attribute of an object. |
|
3 |
delattr(obj, name) |
It is used to delete a specific attribute. |
|
4 |
hasattr(obj,
name) |
It
returns true if the object contains some specific attribute. |
Built-in
class attributes
Along with the other attributes, a Python class also contains some
built-in class attributes which provide information about the class.
The built-in class attributes are given in the below table.
|
SN |
Attribute |
Description |
|
1 |
__dict__ |
It provides the dictionary containing the information about the
class namespace. |
|
2 |
__doc__ |
It
contains a string which has the class documentation |
|
3 |
__name__ |
It is used to access the class name. |
|
4 |
__module__ |
It is
used to access the module in which, this class is defined. |
|
5 |
__bases__ |
It contains a tuple including all base classes. |
0 Comments