What is a Constructor?
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.
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
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
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…