What is a Constructor?
- A constructor is a special method (function) used to initialize the class’s instance members.
- The main goal of constructors is to assign values to the class’s data members when an object of the class is created.
- Constructors are always called when an object is created, and the init() method simulates this. It accepts the self-keyword, which refers to itself (the object), as the first argument, allowing access to the class’s attributes or methods.
Syntax:
class class_name:
def __init__(self):
# body of the constructor
If you then create an example, the constructor will be called, i.e,
object_1= class_name()
Example:
class Student:
# default constructor
def __init__(self):
self.name = "Rohan Sharma"
# a method for printing data members
def print_name(self):
print(self.name)
# creating object of the class
obj = Student()
# calling the instance method using the object obj
obj.print_name()
Output:
Rohan Sharma
By writing Student()
in the code above, we are informing python that obj
is an object of class Student
. And that is exactly when the constructor of that class is called.
More than One Constructor in a Single class:
The object of the class will always call the last constructor if the class has multiple constructors. For instance,
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()
Output:
The second contructor
Built-in class attributes:
There are some built-in class attributes that provide information about the class.
Attribute | Description |
---|---|
__dict__ | The dictionary containing details about the class namespace is made available. |
__doc__ | It contains a string that has the class documentation |
__name__ | It is used to access the class name. |
__module__ | It is used to access the module in which, this class is defined. |
__bases__ | It contains a tuple including all base classes. |
Note: also read about Python Class
Follow Me
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment