Python - OPPS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

MODULE 4

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

Class Inheritance- Syntax, Types and Method overriding


Python supports both procedural and
object-oriented programming approach.

PROCEDURAL PROGRAMMING APPROACH

• Structures a program like a recipe in that it provides a


INTRODUCTION set of steps, in the form of functions and code blocks,
which flow sequentially in order to complete a task.

OBJECT ORIENTED PROGRAMMING


APPROACH
• Provides a means of structuring programs so that
properties and behaviors are bundled into
individual objects.
Object-oriented programming is an approach for modeling
concrete, real-world things like cars as well as relations between
things like companies and employees, students and teachers, etc.
OOP models real-world entities as software objects, which have
some data associated with them and can perform certain functions.

For instance, an object could represent a person with a name


property, age, address, etc., with behaviors like walking, talking,
OOP IN DETAIL breathing, and running

Objects are at the center of the object-oriented programming


paradigm, not only representing the data, as in procedural
programming, but in the overall structure of the program as well.
 Everything in python
is an object.
Example:
a=4
b='hi'
OOP IN PYTHON c=[1,2]
d=('abc',1)
print(type(a)) Output:
<class 'int'>
print(type(b)) <class 'str'>
print(type(c)) <class 'list'>
print(type(d)) <class 'tuple'>
Popular approach to solve a program problem is by creating
objects, which is termed as OOP

An object is an instance of class


OVERVIEW OF
OOP Object has 2 characteristics
TERMINOLOGY Attributes Behaviour

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.

 Ex: We can think of class as a sketch of a dog with labels. It


contains all the details about the name, colors, size etc. Based on
these descriptions, we can study about the dog. Here, dog is an
object.
 “Snowy is a dog” can be translated to “The Snowy object is an
instance of the dog class.” Define once how a dog works and
then reuse it for all dogs.
WHY DO WE NEED CLASS?

 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

• You start with the class keyword to indicate


that you are creating a class, then you add
the name of the class (using CamelCase Syntax
notation , starting with a capital letter) class classname:
• From class, we construct instances. An <statement 1>
.
instance is a specific object created from a
.
class.
<statement n>
Ex:
class dog:
pass
Here, we use class keyword to define an
empty class dog.
 Class consists of Method and Attributes/variables

 Method – is a function that is defined inside a class to manipulate the object data

 Data Member- Is a variable defined in a class


1. Class Variable/attributes
 A class variable is a variable that holds data associated with a class and its objects.
 A variable that is shared by all instances of a class

 Class variables are defined within a class but outside any of class methods

 These variables are not used as frequently as instance variables

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

Argument (self) refers to the object itself


CALLING METHODS IN CLASSES

• Using Methods from Outside a Class


Methods are referenced by using the dot syntax:
<objectName>.<methodName>()

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

• Using Methods from Inside a Class


• When referring to methods from within a class, we must always prefix the function name
with self
(e.g. self.subtract())

>>> class Maths:


... def subtract(self,i,j):
... return i-j
...
...
def testsub(self):
...
print self.subtract(8,4)

Tell Python to use method associated with this


object
CONSTRUCTORS IN PYTHON

 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 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")

# Creates an instance of the class


m = MethodTypes()
# Calls instance method
m.instanceMethod()

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

 To access attributes we can also use the following methods too


 getattr(obj.name[,default])- to access the attribute of object
 getattr(dog1,’age’) returns value of ‘age’ attribute

 hasattr(obj,name) to check if an attribute exists or not


 Hasattr(dog1,’age’) returns true if ‘age’ attribute exists

 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

 delattr(obj,name) to delete an attribute


 delattr(obj,name) delete attribute ‘age’
Example 2
class Employee:
'Common base class for all employees'
empCount = 0
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)
#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(hasattr(emp1, 'salary')) # Returns true if 'salary' attribute exists
print(getattr(emp1, 'salary')) # Returns value of 'salary' attribute
setattr(emp1, 'salary', 4500) # Set attribute 'salary' at 7000
emp1.displayEmployee()
delattr(emp1, 'salary')
emp1.displayEmployee()
del emp1
del emp2
emp1.displayEmployee()

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

emp1 = Employee(“Veer", 2000)


emp2 = Employee(“Zara", 5000)
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__ )
OUTPUT

Employee.__doc__: Common base class for all employees


Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {'__module__': '__main__', '__doc__': 'Common base class for all employees', 'empCount': 2,
'__init__': <function Employee.__init__ at 0x03BE0028>, 'displayCount': <function Employee.displayCount at
0x03BE0070>, 'displayEmployee': <function Employee.displayEmployee at 0x03BE00B8>, '__dict__':
<attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>}
DESTRUCTORS IN PYTHON

 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.
 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 is an important aspect of the object-oriented paradigm.

 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.

 Superclasses are sometimes called ancestors as well.

 There exists a hierarchy relationship between classes.

 It's similar to relationships or categorizations that we know from real life.

 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 derived-class(base class):


<class-suite>

• Class inheritance is designed to model relationships of the type "x is a y" (e.g. "a triangle is a shape")
INHERITANCE

The functions and attributes of a superclass are


inherited by a subclass.

An inherited class can override, modify or augment the functions


and attributes of its parent class.
CREATING SUBCLASSES
EXAMPLE 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

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 represents real-world relationships well.

 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

 Using this type of inheritance,


we can achieve a grandchild
relationship. The grandchild is a
class which inherits all the
properties of the existing child
class.
EXAMPLE
class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class grandChild(Child):
def func3(self):
print("this is function 3")
ob = grandChild()
ob.func1()
ob.func2()
ob.func3()
Output
this is function 1
this is function 2
this is function 3
MULTIPLE
INHERITANCE

 When a child class inherits


from more than one parent
class.
EXAMPLE
class Parent1:

def func1(self):

print("this is function 1")

class Parent2:

def func2(self):

print("this is function 2")

class Child(Parent1 , Parent2):

def func3(self):

print("this is function 3")

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

 More than one child classes


inherit all the properties of the
same parent class.
EXAMPLE
class Parent:
def func1(self):
print("this is function 1")
class Child1(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print("this is function 3")
ob = Child1()
ob1 = Child2()
ob.func1()
ob.func2()
ob1.func1()
ob1.func3()
Output
this is function 1
this is function 2
this is function 1
this is function 3
HYBRID 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 ):

# __init__ is known as the constructor

def __init__(self, name, idnumber):

self.name = name

self.idnumber = idnumber

def display(self):

print(self.name)

print(self.idnumber)

# child class

class Employee( Person ):

def __init__(self, name, idnumber, salary, post):

self.salary = salary

self.post = post

# invoking the __init__ of the parent class

Person.__init__(self, name, idnumber)

# creation of an object variable or an instance

a = Person('Rahul', 886012)

# calling a function of the class Person using its instance

a.display()

b=Employee('Ram',1234,4500,'manager')

print(b.name)
METHOD OVERRIDING
class Parent:

 Method overriding is an ability of any object- def func1(self):


print("this is parent function")
oriented programming language that allows a
subclass or child class to provide a specific
class Child(Parent):
implementation of a method that is already def func1(self):
provided by one of its super-classes or parent print("this is child function")
classes.
ob = Child()
 When a method in a subclass has the same name, ob.func1()
same parameters or signature and same return
Output
type(or sub-type) as a method in its super-class, this is child function
then the method in the subclass is said
to override the method in the super-class.
CALLING THE PARENT’S METHOD WITHIN THE OVERRIDDEN METHOD

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

• Python super() function class Parent:


def func1(self):
provides us the facility to refer
print("this is parent function")
to the parent class explicitly.
class Child(Parent):
• It is basically useful when we
def func1(self):
must call superclass functions.
super().func1()
• It returns the proxy object that print("this is child function")
allows us to refer parent class ob = Child()
by ‘super’. ob.func1()

Output
this is parent function
this is child function

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy