PDF 3
PDF 3
Python Classes/Objects:
Python is an object oriented programming language. Almost everything in Python is an object,
with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating
objects.To create a class, use the keyword class:
Inheritance:
Inheritance is a feature or a process in which, new classes are created from the existing classes.
The new class created is called “derived class” or “child class” and the existing class is known
as the “base class” or “parent class”. The derived class now is said to be inherited from the base
class
When we say derived class inherits the base class, it means, the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new
features to its own. These new features in the derived class will not affect the base class. The
derived class is the specialized class for the base class.
Sub Class: The class that inherits properties from another class is called Subclass or Derived
Class.
Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.
It is divided into the following subtopics:
Why and when to use inheritance?
Modes of Inheritance
Types of Inheritance
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we create these
classes avoiding inheritance then we have to write all of these functions in each of the three
classes as shown below figure:
You can clearly see that the above process results in duplication of the same code 3 times. This
increases the chances of error and data redundancy. To avoid this type of situation, inheritance
is used. If we create a class Vehicle and write these three functions in it and inherit the rest of
the classes from the vehicle class, then we can simply avoid the duplication of data and increase
re-usability. Look at the below diagram in which the three classes are inherited from vehicle
class:
Using inheritance, we have to write the functions only one time instead of three times as we
have inherited the rest of the three classes from the base class (Vehicle).
Polymorphism:
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism is a person who at the same time can have different characteristics.
Like a man at the same time is a father, a husband and an employee. So the same person exhibits
different behavior in different situations. This is called polymorphism.
Binding:
In the context of compiled languages, binding is the link between a function call and the function
definition. When a function is called , the program control binds to the memory address where that
function is defined. Binding generally refers to a mapping of one thing to another.
By default, it matches a function call with the correct function definition at compile time. This
is called static binding. You can specify that the compiler match a function call with the correct
function definition at runtime; this is called dynamic binding.
Class example:
class Person:
name = "john"
age = 35
p1 = Person() # p1 is object of Person class
print(“name is ”+p1.name)
print(“age is” ,p1.age)
_ _init_ _() in Python?
In Python, _ _init_ _()is a special method known as the constructor. It is automatically called when
a new instance (object) of a class is created. The __init__() method allows you to initialize the
attributes (variables) of an object.
class MyClass:
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
obj.display_info()
_ _init_ _() in Python
class Person:
def _ _init_ _(self, name, age):
self.name = name
self.age = age
p1 = Person("John",36)
print(p1.name)
print(p1.age)
The python __init__() method is declared within a class and is used to initialize the attributes
of an object as soon as the object is formed.While giving the definition for an _ _init_ _(self)
method, a default parameter, named ‘self’ is always passed in its argument. This self
represents the object of the class itself.
class Person:
def _init_(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
print("Hello age is ",abc.age)
p1 = Person("John", 36)
p1.myfunc()
output:
Hello my name is John
Hello age is 36
output:
John
36
Hello my name is John
Hello age is 36
Hello my name printed is John
Hi, age is 36
Name: John
Age: 36
Name: John
Age: 36
John
36
Constructor:
Constructors are generally used for instantiating an object. The task of constructors is to
initialize(assign values) to the data members of the class when an object of the class is created.
In Python the __init__() method is called the constructor and is always called when an object is
created.
Syntax of constructor declaration :
def __init__(self):
# body of the constructor
Types of constructors :
default constructor: The default constructor is a simple constructor which doesn’t accept
any arguments. Its definition has only one argument which is a reference to the instance
being constructed.
parameterized constructor: constructor with parameters is known as parameterized
constructor. The parameterized constructor takes its first argument as a reference to the
instance being constructed known as self and the rest of the arguments are provided by the
programmer.
Example of default constructor :
class knowledge:
# default constructor
def __init__(self):
self.name = "self study is best to enhance the knowledge"
# a method for printing data members
def print_info(self):
print(self.name)
# creating object of the class
obj = knowledge()
# calling the instance method using the object obj
obj.print_info()
Output:
self study is best to enhance the knowledge
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
self.first = f
self.second = s
def display(self):
def calculate(self):
obj1.calculate()
obj2.calculate()
obj1.display()
obj2.display()
Output
First number = 1000
Second number = 2000
Addition of two numbers = 3000
First number = 10
Second number = 20
Addition of two numbers = 30
Inheritance:
class Animal:
def speak(self):
print("Animal is parent class")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog belongs to animal class")
float = Dog()
float.bark()
float.speak()
int = Animal()
int.speak()
Multiple Inheritance
A class can be derived from more than one superclass in Python. This is called
multiple inheritance.
For example, A class Bat is derived from superclasses Mammal and WingedAnimal. It makes
sense because bat is a mammal as well as a winged animal.
class Mammal:
def mammal_info(self):
print(" belongs to Mammals class")
class WingedAnimal:
def winged_animal_info(self):
print("Winged animals can flap")
Program2:
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
b = Derived()
print(b.Summation(10,20))
print(b.Multiplication(10,20))
print(b.Divide(10,20))
Function overriding:
Method overriding is an ability of any object-oriented programming language that allows a
subclass or child class to provide a specific implementation of a method that is already provided
by one of its super-classes or parent classes. When a method in a subclass has the same name,
same parameters or signature and same return type(or sub-type) as a method in its super-class,
then the method in the subclass is said to override the method in the super-class.
3#Python Program to call base class overridden method using class name
class Animal:
def sound(self):
print('Animal makes sound.')
class Dog(Animal):
def sound(self):
Animal.sound(self)
print('Dog barks.')
d = Dog()
d.sound()
class Bird(Animal):
def fly(self):
print("It flies in the sky.")
def sing(self):
print("It sings a song.")
print(issubclass(Bird, Animal))
Koyal= Bird()
print(isinstance(Koyal, Bird))
Koyal.eat()
Koyal.sleep()
Koyal.fly()
Koyal.sing()
True
It eats insects.
It sleeps in the night.
It flies in the sky.
It sings a song.
True