Constructors and Inheritance in Python
Day 12 in #100DaysOfCode
Constructors
A constructor is a function that gets called at the time of creating an object. Constructors are responsible for initializing (assigning values) the class's data members when an object of the class is created. The init() function is known as the constructor in Python because it is always called when an object is created.
Syntax of constructor declaration :
def __init__(self):
# body of the constructor
Example: I will create a class called "MyName". It is a pretty obvious one.
class MyName:
# default constructor
def __init__(self):
self.name = "İlke Candan"
# a method for printing data members
def print_MyName(self):
print(self.name)
# creating object of the class
obj = MyName()
# calling the instance method using the object obj
obj.print_MyName()
Result:
İlke Candan
Process finished with exit code 0
Inheritance
Inheritance is a mechanism for reusing code. It allows us to create a class that inherits all of another class's methods and attributes.
The class being inherited from is known as the parent class, sometimes known as the base class.
A child class is one that inherits from another class, often known as a derived class.
Let's take an example where Parent Class is "Books" and Child class is "Sci-Fİ"
# Python code to demonstrate how parent constructors
# are called.
# parent class
class Books(object):
# __init__ is known as the constructor
def __init__(self, name):
self.name = name
def display(self):
print(self.name)
print(self.author)
# child class
class SciFi(Books):
def __init__(self, name, author):
self.author = author
# invoking the __init__ of the parent class
Books.__init__(self, name)
# creation of an object variable or an instance
a = SciFi('Dune', "Frank Herbert")
# calling a function of the class Person using its instance
a.display()
Dune
Frank Herbert
Process finished with exit code 0