Unit 5
Unit 5
1) Object
2) Class
3) Method
4) Inheritance
5) Polymorphism
6) Data Abstraction
7) Encapsulation
• What are classes and objects in Python?
• Python is an object oriented programming language. Unlike
procedure oriented programming, where the main
emphasis is on functions, object oriented programming
stress on objects.
• Object is simply a collection of data (variables) and
methods (functions) that act on those data. And, class is a
blueprint for the object.
• We can think of class as a sketch (prototype) of a house. It
contains all the details about the floors, doors, windows
etc. Based on these descriptions we build the house. House
is the object.
• As, many houses can be made from a description, we can
create many objects from a class. An object is also called an
instance of a class and the process of creating this object is
called as instantiation
Syntax for creating a Class
Obj=MyClass()
print(Obj.a)
Obj.func()
print(Obj.__doc__)
• self represents the instance of the class. By using the “self”
keyword we can access the attributes and methods of the
class in python. It binds the attributes with the given
arguments.
3. It simulates the real world entity. It doesn't simulate the real world. It
So real-world problems can be works on step by step instructions
easily solved through oops. divided into small parts called
functions.
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
# A Sample class with init method
class Person:
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p1.say_hi()
p2.say_hi()
p3.say_hi()
• class car:
•
• # init method or constructor
• def __init__(self, model, color):
• self.model = model
• self.color = color
•
• def show(self):
• print("Model is", self.model )
• print("color is", self.color )
•
• # both objects have different self which
• # contain their attributes
• audi = car("audi a4", "blue")
• ferrari = car("ferrari 488", "green")
•
• audi.show() # same output as car.show(audi)
• ferrari.show() # same output as car.show(ferrari)
•
• # Behind the scene, in every instance method
• # call, python sends the instances also with
• # that method call like car.show(audi)
Python Constructor
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("John")
• Example demonstrating parameterized
constructor :
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("Ravi",1)
emp2 = Employee("Amol",2)
emp1.display()
emp2.display()
Python destructor
• Destructors are called when an object gets destroyed. In
Python, destructors are not needed as much needed in C++
because Python has a garbage collector that handles memory
management automatically.
• The __del__() method is a known as a destructor method in
Python. It is called when all references to the object have been
deleted i.e when an object is garbage collected.
def __del__(self):
# body of destructor
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
obj = Employee()
del obj
Python In-built class functions
S.r Function Description
1 getattr(obj,name,default) It is used to access the attribute
of the object.
print(hasattr(s,'id'))
# deletes the attribute age
delattr(s,'age')
# this will give an error since the attribute age has been deleted
Built-in class attributes
SN Attribute Description
1 __dict__ It provides the dictionary containing
the information about the class
namespace.
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Method Overloading
Like other languages (for example method overloading in C++) do,
python does not supports method overloading. We may overload the
methods but can only use the latest defined method.
Example :
product(4, 5)
product(4, 5, 5)
• Method overloading in python
obj = Person()
obj.sayHello()
obj.sayHello(‘VVP')
def add(datatype, *args):
if datatype =='int':
answer = 0
if datatype =='str':
answer =‘ ‘
for x in args:
answer = answer + x
print(answer)
def getName(self):
return self.name
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
emp = Person("Geek1")
print(emp.getName(), emp.isEmployee())
emp = Employee("Geek2")
print(emp.getName(), emp.isEmployee())
Multi-Level inheritance
d = DogChild()
d.bark()
d.speak()
d.eat()
Multiple inheritance
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()
Method Overriding
• We can provide some specific implementation of the
parent class method in our child class. When the
parent class method is defined in the child class
with some specific implementation, then the
concept is called method overriding. We may need
to perform method overriding in the scenario where
the different definition of a parent class method is
needed in the child class
Example:
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Super () method
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
super().speak()
print("Barking")
d = Dog()
d.speak()
Composition Classes
• Composition is a concept that models a has a relationship. It enables creating
complex types by combining objects of other types.
• For example, your Horse class can be composed by another object of type Tail.
Composition allows you to express that relationship by saying a Horse has
a Tail.
• Both Horse and Dog classes can leverage the functionality of Tail through
class Salary:
def __init__(self, pay):
self.pay = pay
def get_total(self):
return (self.pay*12)
class Employee:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
self.obj_salary = Salary(self.pay)
def annual_salary(self):
return "Total: " + str(self.obj_salary.get_total() + self.bonus)
obj_emp = Employee(600, 500)
print(obj_emp.annual_salary())
# specializing inherited methods
class Super:
def method(self):
print("In super.method")
def delegate(self):
self.action()
class Inheritor(Super):
print('\n'"Inheritor....")
pass
class Replacer(Super):
def method(self):
print('\n'"Replacer....")
print("In Replacer.method")
class Extender(Super):
def method(self):
print('\n'"Extender....")
Super.method(self)
print("In Extender.method")
class Provider(Super):
def action(self):
print('\n'"Provider....")
i = Inheritor()
r = Replacer()
e = Extender()
i.method()
r.method()
e.method()
x = Provider()
x.delegate()
O U
K Y
A N
TH