0% found this document useful (0 votes)
43 views12 pages

PDF 3

Uploaded by

Nitesh Sheoran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views12 pages

PDF 3

Uploaded by

Nitesh Sheoran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

OOPs concept:

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.

Here’s an example to illustrate the usage of __init__:

class MyClass:

def __init__(self, name, age):

self.name = name

self.age = age

def display_info(self):

print(f"Name: {self.name}")

print(f"Age: {self.age}")

# Creating an instance of MyClass

obj = MyClass("John", 25)

# Accessing attributes and calling methods

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)

How Does _ _init_ _() Method Work?

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

Write output of following program


class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(abc):
print("Hello my name printed is "+abc.name)
print("Hi, age is ",abc.age)
def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
def display_info1(sf):
print(f"Name: {sf.name}")
print(f"Age: {sf.age}")
def display_info2(x):
print(x.name)
print(x.age)
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
print("Hello my name is " + p1.name)
print("Hello age is ",p1.age)
p1.myfunc()
p1.display_info()
p1.display_info1()
p1.display_info2()

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

def __init__(self, f, s):

self.first = f

self.second = s

def display(self):

print("First number = " + str(self.first))

print("Second number = " + str(self.second))

print("Addition of two numbers = " + str(self.answer))

def calculate(self):

self.answer = self.first + self.second

# creating object of the class


# this will invoke parameterized constructor

obj1 = Addition(1000, 2000)

# creating second object of same class

obj2 = Addition(10, 20)

# perform Addition on obj1

obj1.calculate()

# perform Addition on obj2

obj2.calculate()

# display result of obj1

obj1.display()

# display result of obj2

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:

A class can be derived from superclass in Python. This is called 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")

class Bat(Mammal, WingedAnimal):


pass

# create an object of Bat class


b1 = Bat()
b1.mammal_info()
b1.winged_animal_info()

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.

1#Python program to implement method overriding


class Animal:
def sound(self):
print('Animal makes sound.')
class Dog(Animal):
def sound(self):
print('Dog barks.')
d = Dog()
d.sound()
2#Python program to implement method overriding
class Animal:
def sound(self):
print('Animal makes sound.')
class Dog(Animal):
def sound(self):
super().sound()
print('Dog barks.')
d = Dog()
d.sound()

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()

issubclass() and isinstance()


class Animal:
def eat(self):
print("It eats insects.")
def sleep(self):
print("It sleeps in the night.")

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

You might also like