Python - OPPS
Python - OPPS
Python - OPPS
OBJECT ORIENTED
PROGRAMMING IN PYTHON
Overview of OOP terminology
Creating classes
OBJECT
Creating Instance objects
ORIENTED
PROGRAMMING Accessing Attributes
IN PYTHON Built-in class attributes
Destroying objects
Example:
Dog is an object
Name, age, color are attributes Barking, running are behaviors
1. POLYMORPHISM
In literal sense, Polymorphism means the ability to take various forms.
Polymorphism is a very important concept in programming. It refers to the use of a single type entity (method,
operator or object) to represent different types in different scenarios.
Example: Polymorphism in addition operator
We know that the + operator is used extensively in Python programs. But it does not have a single usage.
For integer data types, + operator is used to perform arithmetic addition operation.
Similarly, for string data types, + operator is used to perform concatenation.
Here, we can see that a single operator + has been used to carry out different operations for distinct data types. This
is one of the simplest occurrences of polymorphism in Python
2. Encapsulation
Used to restrict access to methods and variables
In Encapsulation, code and data are wrapped together with in a single unit from being modified by accident
3. Data Abstraction
Data abstraction and encapsulation but are often used as synonyms, because data abstraction is achieved through
encapsulation
Abstraction means hiding the complexity and only showing the essential features of the object.
So in a way, Abstraction means hiding the real implementation and we, as a user, knowing only how to use it.
Real world example would be a TV set where we enjoy programs with out knowing the inner details of how TV works.
4. Inheritance
Inheritance is a mechanism, by which one class acquires, all the properties and behaviors of another class.
The class whose members are inherited is called the Super class (or base class), and the class that inherits those
members is called the Sub class (or derived class).
Classes and Objects
Object-‐Oriented Programming (OOP): A programming paradigm that involves designing programs around
concepts represented as "objects"
Python supports OOP through the provision of classes.
Terminology
Class: A collection of functions and attributes, attached to a specific name, which represents an abstract concept.
Attribute: A named piece of data (i.e. variable associated with a class.
Object: A single concrete instance generated from a class
WHAT IS A CLASS?
It’s a special data type that contains certain attributes to define
an object
A class is a blueprint for the object.
The primitive data structures available in Python, like numbers, strings, and lists are designed to
represent simple things like the cost of something, the name of a poem, and your favorite colors,
respectively.
What if you wanted to represent something much more complicated?
For example, let’s say you wanted to track a number of different animals. If you used a list, the first
element could be the animal’s name while the second element could represent its age.
How would you know which element is supposed to be which? What if you had 100 different animals?
Are you certain each animal has both a name and an age, and so forth? What if you wanted to add
other properties to these animals? This lacks organization, and it’s the exact need for classes.
In the case of an animal, we could create an animal class to track properties about the Animal like the
name and age.
It’s important to note that a class just provides structure—it’s a blueprint for how something should be
defined, but it doesn’t actually provide any real content itself.
The animal class may specify that the name and age are necessary for defining an animal, but it will not
actually state what a specific animal’s name or age is.
It may help to think of a class as an idea for how something should be defined.
OBJECTS
While the class is the blueprint, an instance is a copy of the class with actual values, literally an
object belonging to a specific class. It’s not an idea anymore; it’s an actual animal, like a dog
named Roger who’s eight years old.
Put another way, a class is like a form or questionnaire. It defines the needed information.
After you fill out the form, your specific copy is an instance of the class; it contains actual
information relevant to you.
You can fill out multiple copies to create many different instances, but without the form as a
guide, you would be lost, not knowing what information is required. Thus, before you can
create individual instances of an object, we must first specify what is needed by defining a
class.
Creating instance Objects
To create instance of a class , you can call the class using class name and pass in what ever arguments its
__init__ method accepts
d1=dog('snowy',3)
d2=dog('bruno’,5)
Accessing attributes
You can access the objects attributes using the dot(.) operator with the object
Class variable would be accessed using class name
Ex:
d1=dog('snowy',3)
d2=dog('bruno’,5)
print("total dogs %d"%dog.dogcount)
CLASSES AND OBJECTS
Class
Objects
Creating Classes
Defining a class in Python is done using the class keyword, followed by an indented block with the class contents.
class <Classname>:
data1 = value1
Data attributes
...
dataM = valueM
def <function1>(self,arg1,...,argK):
<block>
Methods
...
def <functionN>(self,arg1,...,argK):
<block>
HOW TO DEFINE A CLASS IN PYTHON
Method – is a function that is defined inside a class to manipulate the object data
Class variables are defined within a class but outside any of class methods
2. Instance Variable/attributes
A variable that is defined inside a method and belong only to the current instance of a class
DEFINING METHODS IN CLASSES
• A class definition block can include multiple methods.
• These represent the functionality or behaviors that are associated with the
class
>>> m = Maths()
No need to specify value for
>>> m.subtract(10,5)
self, Python does this
5 automatically
>>>m.add(6,7)
13
CALLING METHODS IN CLASSES
The task of constructors is to initialize(assign values) to the data members of the class when an object of class
is created.
In Python the __init__() method is called the constructor and is always called when an object is created.
syntax
def __init__(self):
# body of the constructor
TYPES OF CONSTRUCTORS :
1. Default constructor :
The default constructor is simple constructor which doesn’t accept any arguments.
It’s definition has only one argument which is a reference to the instance being constructed.
Ex : def __init__(self):
print('i am in init')
2. Parameterized constructor :
Constructor with parameters is known as parameterized constructor.
The parameterized constructor take 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.
Ex: def __init__(self,name,age):
self.name=name
self.age=age
DIFFERENT METHOD TYPES IN PYTHON
In python there are three different method types. The static method, the class method and the instance method. Each
one of them have different characteristics and should be used in different situations.
Static methods
A static method in python must be created by decorating it with @staticmethod in order to let python now that the
method should be static.
The main characteristics of a static method is that they can be called without instantiating the class.
This methods are self contained, meaning that they cannot access any other attribute or call any other method within
that class.
The main characteristic you could use a static method when you have a class but you do not need an specific
instance in order to access that method.
For example if you have a class called Math and you have a method called factorial (calculates the factorial of a
number).
You probably won’t need a specific instance to call that method so you could use a static method.
Class method
Methods which have to be created with the decorator @classmethod, this methods share a characteristic with the
static methods and that is that they can be called without having an instance of the class.
The difference relies on the capability to access other methods and class attributes but no instance attributes
Instance Methods
This method can only be called if the class has been instantiated.
Once an object of that class has been created the instance method can be called and can access all the attributes
of that class through the reserved word self.
An instance method is capable of creating, getting and setting new instance attributes and calling other instance,
class and static methods
EXAMPLE 1 OF THE DIFFERENT METHOD TYPES
class MethodTypes:
name = "Ragnar"
def instanceMethod(self):
# Creates an instance atribute through keyword self
self.lastname = "Lothbrock"
print(self.name)
print(self.lastname)
@classmethod
def classMethod(cls):
# Access a class atribute through keyword cls
cls.name = "Lagertha"
print(cls.name)
@staticmethod
def staticMethod():
print("This is a static method")
MethodTypes.classMethod()
MethodTypes.staticMethod()
Example 2 of the different method types
class Employee:
'Common base class for all employees'
empCount = 0
currentyear= 2020
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
@classmethod
def yearofbirth(cls,birthyear):
return cls.currentyear-birthyear
@staticmethod
def department(dept):
return dept
def getname(self):
return self.name
def __del__(self):
print("destructor is called")
#This would create first object of Employee class"
emp1 = Employee("veer", 2000)
#This would create second object of Employee class"
emp2 = Employee("zara", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
emp1.salary = 7000
emp1.displayEmployee()
emp2.name = 'xyz'
emp2.displayEmployee()
print(emp1.getname(),Employee.yearofbirth(1990), Employee.department('IT'))
print(emp2.getname(), Employee.yearofbirth(1991), Employee.department('HR’))
del emp1
Output
Name : veer , Salary: 2000
Name : zara , Salary: 5000
Total Employee 2
Name : veer , Salary: 7000
Name : xyz , Salary: 5000
veer 30 IT
xyz 29 HR
destructor is called
EXAMPLE 1
class dog:
dogcount=0 #class variable
def __init__(self,name,age):
print('i am in init')
self.name=name #instance variable
self.age=age #instance variable
dog.dogcount+=1
def walk(self):
print("hi i am %s and i am of age %d and i am walking"%(self.name,self.age))
d1=dog('snowy',3) Output:
d2=dog('bruno',5) i am in init
d1.walk() i am in init
d2.walk() hi i am snowy and i am of age 3 and i am walking
print("total dogs %d"%dog.dogcount) hi i am bruno and i am of age 5 and i am walking
total dogs 2
You can add , remove, modify attributes of classes and objects at any time
Dog1.age=7
Del dog1.age
setattr(obj,name,value) to set an attribute. If attribute does not exist, then it would be created.
setattr(dog1,’age’,9) set attribute ‘age’ at 9
Output
Name : veer , Salary: 2000
Name : zara , Salary: 5000
Total Employee 2
Name : veer , Salary: 7000
Name : xyz , Salary: 5000
True
7000
Name : veer , Salary: 4500
destructor is called
destructor is called
Traceback (most recent call last):
File "C:\Users\kusum\AppData\Local\Programs\Python\Python38-32\oop.py", line 38, in <module>
emp1.displayEmployee()
NameError: name 'emp1' is not defined
BUILT-IN CLASS ATTRIBUTES
Every Python class keeps following built-in attributes and they can be accessed using dot operator like any
other attribute −
__dict__ − Dictionary containing the class's namespace.
__doc__ − Class documentation string or none, if undefined.
__name__ − Class name.
__module__ − Module name in which the class is defined. This attribute is "__main__" in interactive mode.
__bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base
class list.
For the Employee class let us try to access all these attributes −
Example:
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
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.
Syntax of destructor declaration :
def __del__(self):
# body of destructor
EXAMPLE :
Here is the simple example of destructor. By using del keyword we deleted the all references of object ‘obj’,
therefore destructor invoked automatically.
class Employee:
# Initializing
def __init__(self):
Output:
print('Employee created.') Employee created.
Destructor called, Employee deleted.
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj
INHERITANCE
INHERITANCE
Inheritance provides code reusability to the program because we can use an existing class to create a new
class instead of creating it from scratch.
Python not only supports inheritance but multiple inheritance as well.
Inheritance is the mechanism of deriving new classes from existing ones. By doing this we get a hierarchy of
classes.
In most class-based object-oriented languages, an object created through inheritance (a "child object")
acquires all the properties and behaviors of the parent object.
INHERITANCE
The class from which a class inherits is called the parent or superclass.
A class which inherits from a superclass is called a subclass, also called heir class or child class.
Think about vehicles, for example. Bikes, cars, buses and trucks are vehicles.
Pick-ups, vans, sports cars, convertibles and estate cars are all cars and by being cars they are vehicles as well.
We could implement a vehicle class in Python, which might have methods like accelerate and brake.
Cars, Buses and Trucks and Bikes can be implemented as subclasses which will inherit these methods from vehicle.
INHERITANCE
INHERITANCE
Syntax:
• Class inheritance is designed to model relationships of the type "x is a y" (e.g. "a triangle is a shape")
INHERITANCE
Output
dog barking
Animal Speaking
EXAMPLE 2
class SHAPE:
cl=123
def __init__(self):
self.color=(0,0,0)
class RECTANGLE(SHAPE):
def __init__( self, w, h ):
super().__init__() # SHAPE.__init__(self)
self.width = w
self.height = h
def AREA( self ):
return self.width*self.height
r1=RECTANGLE(10,5)
print(r1.width)
print(r1.height)
print(r1.AREA())
print(r1.cl)
print(r1.color)
BENEFITS OF INHERITANCE
It provides reusability of a code. We don’t have to write the same code again and again. Also, it allows
us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of
B would automatically inherit from class A.
DIFFERENT FORMS
OF INHERITANCE:
Single inheritance: When a
child class inherits from only
one parent class, it is called
as single inheritance.
EXAMPLE
class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print("this is function two ")
ob = Child()
ob.func1()
ob.func2()
Output
this is function one
this is function two
MULTILEVEL
INHERITANCE
def func1(self):
class Parent2:
def func2(self):
def func3(self):
ob = Child()
ob.func1()
ob.func2()
ob.func3()
Output
this is function 1
this is function 2
this is function 3
HIERARCHICAL
INHERITANCE IN PYTHON
Hybrid inheritance is a
combination of multiple and
multilevel inheritance. More
than one child class inherits a
parent class. Those two child
class, in turn, acts as the parent
class for a grandchild class as
shown in the image.
EXAMPLE
class Parent:
def func1(self):
print("this is function one")
class Child1(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print(" this is function 3")
class grand_Child(Child1,Child2):
def func4(self):
print(" this is function 4")
ob = grand_Child()
ob.func1()
Output
this is function one
PYTHON CODE TO DEMONSTRATE HOW PARENT CONSTRUCTORS ARE CALLED.
class Person( object ):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
# child class
self.salary = salary
self.post = post
a = Person('Rahul', 886012)
a.display()
b=Employee('Ram',1234,4500,'manager')
print(b.name)
METHOD OVERRIDING
class Parent:
class Parent:
Parent class methods can also be called def func1(self):
within the overridden methods. This can print("this is parent function")
generally be achieved by two ways. class Child(Parent):
def func1(self):
Using Classname: Parent’s class methods Parent.func1(self)
can be called by using the Parent print("this is child function")
classname.method inside the overridden
method. ob = Child()
ob.func1()
Output
this is parent function
this is child function
SUPER() METHOD
Output
this is parent function
this is child function