Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
What is Constructor in Python?
A constructor is a special type of method (function) which is used to initialize the instance members of the class.
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.
How to Create the constructor in python ?
In Python, the method the __init__() simulates the constructor of the class. This method is called when the class is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method of the class. We can pass any number of arguments at the time of creating the class object, depending upon the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a constructor, even if it simply relies on the default constructor.
Constructors can be of two types.
File name : index.py
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("Sana", 101)
emp2 = Employee("Mahira", 102)
# accessing display() method to print employee 1 information
emp1.display()
# accessing display() method to print employee 2 information
emp2.display()
Output:
ID: 101
Name: sana
ID: 102
Name: Mahira
Counting the number of objects of a class
The constructor is called automatically when we create the object of the class.
File name : index.py
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)
Non-Parameterized Constructo :-
The non-parameterized constructor uses when we do not want to manipulate the value or the constructor that has only self as an argument.
File name : index.py
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("Mahira Mahtab")
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self.
File name : index.py
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("Sana")
student.show()
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.
File name : index.py
class Student:
roll_num = 101
name = "Sana"
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
Output:
101 sana
Constructor Overloading in python
what happen if we declare the two same constructors in the class.
File name : index.py
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()
Output:
The Second Constructor
he object st called the second constructor whereas both have the same configuration. The first method is not accessible by the st object. Internally, the object of the class will always call the last constructor if the class has multiple constructors.
Note: The constructor overloading is not allowed in Python.
Python built-in class functions
File name : index.py
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.
File name : index.py
class Student:
def __init__(self, name, id, age):
self.name = name
self.id = id
self.age = age
# creates the object of the class Student
s = Student("John", 101, 22)
# prints the attribute name of the object s
print(getattr(s, 'name'))
# reset the value of attribute age to 23
setattr(s, "age", 23)
# prints the modified value of age
print(getattr(s, 'age'))
# prints true if the student contains the attribute with name id
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print(s.age)
output :-
John
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
a Python class also contains some built-in class attributes which provide information about the class.
File name : index.py
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.
File name : index.py
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
File name : index.py