Leela Soft Python3 Madhu
Object-Oriented Programming
OOA, OOD and OOP:
Object-Oriented Analysis, Object-Oriented Design and Object-Oriented Programming How are
the three different activities related? Is one activity more important than any of the others?
✓ OOA
o Find objects
o Organize objects
o Describe objects behaviors
o Describe objects internals
o Describe objects interacts
o Different from traditional analysis method in that
▪ Around objects
▪ Consider both state and behaviors of objects
• ER diagram considers only data
• Flow chart considers only behavior
o The output is use cases and object conceptual model
o Technology independent
✓ OOD
o Apply constraints to OOA output (object conceptual model)
o The constraints include
▪ Hardware and software platform
▪ Performance
▪ Storage
▪ Transactions
▪ Usability
▪ Availability
▪ Scalability
▪ Budget and time
▪ Resources
o Detailed descriptions of how this system work on concrete technologies
✓ OOP
o Encapsulation
o Polymorphism
o Inheritance (IS-A relationship)
o Abstraction
www.leelasoft.com Cell: 78-42-66-47-66 1
Leela Soft Python3 Madhu
Object-Oriented Programming:
OOP is a type of programming in which programmers define not only the data type of a data
structure, but also the types of operations that can be applied to the data structure.
One of the main advantages of object-oriented programming over procedural programming is
that they enable programmers to create modules that do not need to be changed when a new
type of object is added. A programmer can simply create a new object that inherits many of its
features for existing objects. This makes object-oriented programs easier to modify.
Overview of OOP Terminology:
✓ Class: A class is a blueprint for objects- one class for any number of objects of that type.
✓ Class variable: A variable that is shared by all instances of a class.
✓ Data member: A class variable or instance variable that holds data associated with a
class and its objects.
✓ Method: A special kind of function that is defined in a class definition.
✓ Object: A unique instance of a data structure that is defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
What is Class:
✓ In Python everything is an object. To create objects we required some Model or Plan or
Blue print, which is nothing but class.
✓ We can write a class to represent properties (attributes) and actions (behavior) of
object.
✓ Properties can be represented by variables
✓ Actions can be represented by Methods.
✓ Hence class contains both variables and methods.
Creating Class:
The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon (:).
Syntax:
class ClassName:
'''Optional! class documentation string'''
class_suite
1. The class has a documentation string, which can be accessed via
ClassName.__doc__.
www.leelasoft.com Cell: 78-42-66-47-66 2
Leela Soft Python3 Madhu
2. The class_suite consists of all the component statements defining class members,
data attributes and functions.
Example:
class fruit:
"""
This Python3 class creates instances of fruits
"""
Example:
class MyClass:
x = 5
print(MyClass)
What is Object:
Physical existence of a class is nothing but object. We can create any number of objects for a
class.
Instantiate an Object in Python
Creating a new object from a class is called instantiating an object. We can instantiate a new
Class_Name object by typing the name of the class, followed by opening and closing
parentheses.
Syntax to create object:
referencevariable = classname()
What is Reference Variable:
✓ The variable which can be used to refer object is called reference variable.
✓ By using reference variable, we can access properties and methods of object.
Example:
class Person:
pass
p1 = Person()
p2 = Person()
www.leelasoft.com Cell: 78-42-66-47-66 3
Leela Soft Python3 Madhu
Built-In Class Attributes:
The following are 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.
Example:
class Employee:
"""
Common base class for all employees
"""
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__)
The self argument:
✓ The self is the default variable which is always pointing to current object (like this
keyword in Java)
✓ By using self we can access instance variables and instance methods of object.
Note: 1
The self should be first parameter inside constructor
def __init__(self):
pass
Note: 2
The self should be first parameter inside instance methods
def m1(self):
pass
www.leelasoft.com Cell: 78-42-66-47-66 4
Leela Soft Python3 Madhu
Constructor in Python:
✓ A constructor is a special kind of method that Python calls when it instantiates an object
using the definitions found in our class.
✓ The constructor to perform tasks such as initializing (assigning values to) any instance
variables that the object will need when it starts.
✓ Constructors can also verify that there are enough resources for the object and perform
any other start-up task.
✓ The name of a constructor is always the same, __init__().
✓ The constructor can accept arguments when necessary to create the object.
✓ When we create a class without a constructor, Python automatically creates a default
constructor.
Example:
def __init__(self, name, rollno, marks):
self.name = name
self.rollno = rollno
self.marks = marks
Program to demonstrate constructor will execute only once per object:
class Test:
def __init__(self):
print("Constructor exeuction...")
def m1(self):
print("Method execution...")
t1 = Test()
t2 = Test()
t3 = Test()
t1.m1()
Output:
Constructor exeuction...
Constructor exeuction...
Constructor exeuction...
Method execution...
Program:
class Student:
'''This is student class with required data'''
def __init__(self, x , y, z):
self.name = x
www.leelasoft.com Cell: 78-42-66-47-66 5
Leela Soft Python3 Madhu
self.rollno = y
self.marks = z
def display(self):
print("StudentName:{}\nRollno:{}\nMarks:{}".format(self.name,
self.rollno, self.marks))
s1 = Student("Leela", 101, 80)
s1.display()
s2 = Student("Rohith", 102, 100)
s2.display()
Python Methods:
✓ A Python method is like a Python function, but it must be called on an object. And to
create it, you must put it inside a class.
✓ A method has a name, and may take parameters and have a return statement.
Types of Methods:
Inside Python class 3 types of methods are allowed they are:
✓ Instance Methods
✓ Static Methods
✓ Class Methods
Instance Methods:
✓ Inside method implementation if we are using instance variables then such type of
methods are called instance methods.
✓ Inside instance method declaration, we have to pass self variable.
def m1(self):
pass
✓ By using self variable inside method we can able to access instance variables.
✓ Within the class we can call instance method by using self variable and from outside of
the class we can call by using object reference.
Example:
class Student:
def __init__(self,name,marks):
self.name=name
self.marks=marks
def display(self):
print('Hi',self.name)
www.leelasoft.com Cell: 78-42-66-47-66 6
Leela Soft Python3 Madhu
print('Your Marks are:',self.marks)
def grade(self):
if self.marks>=60:
print('You got First Grade')
elif self.marks>=50:
print('Yout got Second Grade')
elif self.marks>=35:
print('You got Third Grade')
else:
print('You are Failed')
n=int(input('Enter number of students:'))
for i in range(n):
name=input('Enter Name:')
marks=int(input('Enter Marks:'))
s= Student(name,marks)
s.display()
s.grade()
print()
Class Method:
Inside method implementation if we are using only class variables (static variables), then such
type of methods we should declare as class method.
We can declare class method explicitly by using @classmethod decorator.
The @classmethod decorator, is a built-in function decorator that is an expression that gets
evaluated after our function is defined. The result of that evaluation shadows our function
definition.
A class method receives the class as implicit first argument, just like an instance method
receives the instance.
We can call classmethod by using classname or object reference variable.
Syntax:
class class_name(object):
@classmethod
def method_name(cls, arg1, arg2, ...):
pass
Example:
class Animal:
legs=4
www.leelasoft.com Cell: 78-42-66-47-66 7
Leela Soft Python3 Madhu
@classmethod
def walk(cls,name):
print('{} walks with {} legs...'.format(name, cls.legs))
Animal.walk('Dog')
Animal.walk('Cat')
Points to Remember:
1. A class method is a method which is bound to the class and not the object of the class.
2. They have the access to the state of the class as it takes a class parameter that points to the
class and not the object instance.
3. It can modify a class state that would apply across all the instances of the class. For
example, it can modify a class variable that will be applicable to all the instances.
Static Method:
✓ In general these methods are general utility methods.
✓ Inside these methods we won't use any instance or class variables.
✓ Here we won't provide self or cls arguments at the time of declaration.
✓ We can declare static method explicitly by using @staticmethod decorator
✓ We can access static methods by using classname or object reference
Syntax:
class class_name(object):
@staticmethod
def method_name(arg1, arg2, ...):
pass
Example:
class MathDemo:
@staticmethod
def add(x,y):
print('The Sum:',x+y)
@staticmethod
def product(x,y):
print('The Product:',x*y)
@staticmethod
def average(x,y):
print('The average:',(x+y)/2)
MathDemo.add(10,20)
MathDemo.product(10,20)
MathDemo.average(10,20)
www.leelasoft.com Cell: 78-42-66-47-66 8
Leela Soft Python3 Madhu
Note: In general, we can use only instance and static methods. Inside static method we can
access class level variables by using class name.
✓ A static method is also a method which is bound to the class and not the object of the class.
✓ A static method can’t access or modify class state.
✓ It is present in a class because it makes sense for the method to be present in class.
Class method vs Static Method:
✓ A class method takes cls as first parameter while a static method needs no specific
parameters.
✓ A class method can access or modify class state while a static method can’t access or
modify it.
✓ In general, static methods know nothing about class state. They are utility type methods
that take some parameters and work upon those parameters. On the other hand class
methods must have class as parameter.
✓ We use @classmethod decorator in python to create a class method and we use
@staticmethod decorator to create a static method in python.
Differences between Methods and Constructors:
Methods Constructors
Name of method can be any name Constructor name should be always __init__
Method will be executed if we call that Constructor will be executed automatically at
method the time of object creation.
Per object, method can be called any Per object, Constructor will be executed only
number of times. once
Inside method we can write business logic Inside Constructor we have to declare and
initialize instance variables
Calling a Class Method from Another Class Method
class Test:
@classmethod
def m1(cls):
print("Class Method m1")
class Emp:
@classmethod
def m2(cls):
print("Class method of Emp")
Test.m1()
e = Emp()
e.m2()
www.leelasoft.com Cell: 78-42-66-47-66 9
Leela Soft Python3 Madhu
Types of variables:
In Python 3 types of variables are declared inside a class. They are
1. Instance Variables(non-static)
2. Static Variables/class level variables
3. Local variables
1. Instance Variables or Object Variables:
If the value of a variable is varied from object to object, then such type of variables are called
instance variables.
For every object a separate copy of instance variables will be created.
Where we can declare Instance variables:
✓ Inside Constructor by using self parameter.
✓ Inside Instance Method by using self parameter.
✓ Outside of the class by using object reference variable.
Inside Constructor by using self parameter:
We can declare instance variables inside a constructor by using self parameter. Once we
create object, automatically these variables will be added to the object.
Example:
class Employee:
def __init__(self):
self.eno = 100
self.ename = 'Leela'
self.esal = 10000
e = Employee()
print(e.__dict__)
Inside Instance Method by using self variable:
We can also declare instance variables inside instance method by using self variable. If any
instance variable declared inside instance method, that instance variable will be added once we
call that method.
Example:
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
www.leelasoft.com Cell: 78-42-66-47-66 10
Leela Soft Python3 Madhu
t=Test()
t.m1()
print(t.__dict__)
Outside of the class by using object reference variable:
We can also add instance variables outside of a class to a particular object.
Example:
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t=Test()
t.m1()
t.d=40
print(t.__dict__)
How to access Instance variables?
We can access instance variables with in the class by using self variable and outside of the
class by using object reference.
Example:
class Test:
def __init__(self):
self.a=10
self.b=20
def display(self):
print(self.a)
print(self.b)
t=Test()
t.display()
print(t.a,t.b)
Instance Variables (non-static) Summary:
1. If the value of a variable is varied from object to object, then we should go for instance
variables.
2. For every object a separate copy of instance variables will be created.
3. In general, inside constructor we have to declare by using self parameter.
4. How to access instance variables:
a. Within the constructor by using self
b. But outside of the class by using reference variable.
www.leelasoft.com Cell: 78-42-66-47-66 11
Leela Soft Python3 Madhu
5. By using one object reference if we perform any changes to the instance variables, the
changes won't be affected to remaining objects.
6. Inside instance methods we can declare instance variables using self. When we call that
method, those variables will be added to our object.
7. Outside of the class by using reference variable we can declare instance variable also. If
we are adding any instance variable of an object outside of the class, those instance
variables available only for that particular object.
8. Where we can declare an instance variable?
a. Inside Constructor by using self variable
b. Inside Instance Method by using self variable
c. Outside of the class by using object reference variable
Class variables or Static variables:
If the value of a variable is not varied from object to object, such type of variables we have to
declare with in the class directly but outside of methods. Such types of variables are called
Static variables.
For total class only one copy of static variable will be created and shared by all objects of that
class.
We can access static variables either by class name or by object reference. But it is
recommended to access by using class name.
Various places to declare static variables:
✓ In general, we can declare within the class directly but from outside of any method
✓ Inside constructor by using class name
✓ Inside instance method by using classname
✓ Inside classmethod by using either classname or cls variable
✓ Inside static method by using classname.
Example: To declare static variable
class Test:
a=10
def __init__(self):
Test.b=20
def m1(self):
Test.c=30
@classmethod
def m2(cls):
cls.d1=40
Test.d2=400
www.leelasoft.com Cell: 78-42-66-47-66 12
Leela Soft Python3 Madhu
@staticmethod
def m3():
Test.e=50
print(Test.__dict__)
t=Test()
print(Test.__dict__)
t.m1()
print(Test.__dict__)
Test.m2()
print(Test.__dict__)
Test.m3()
print(Test.__dict__)
Test.f=60
print(Test.__dict__)
How to access static variables:
✓ Inside constructor: by using either self or classname
✓ Inside instance method: by using either self or classname
✓ Inside class method: by using either cls variable or classname
✓ Inside static method: by using classname
✓ From outside of class: by using either object reference or classname
Example:
class Test:
a=100
def __init__(self):
print(self.a)
print(Test.a)
def m1(self):
print(self.a)
print(Test.a)
@classmethod
def m2(cls):
print(cls.a)
print(Test.a)
@staticmethod
www.leelasoft.com Cell: 78-42-66-47-66 13
Leela Soft Python3 Madhu
def m3():
print(Test.a)
t=Test()
print(Test.a)
print(t.a)
t.m1()
t.m2()
t.m3()
Where we can modify the value of static variable:
Anywhere either with in the class or outside of class we can modify by using classname. But
inside classmethod, by using cls variable also we can modify the value.
Example:
class Test:
a=777
@classmethod
def m1(cls):
cls.a=888
@staticmethod
def m2():
Test.a=999
print(Test.a)
Test.m1()
print(Test.a)
Test.m2()
print(Test.a)
Local variables:
Sometimes to meet temporary requirements of programmer, we can declare variables inside a
method directly, such type of variables are called local variable or temporary variables.
Local variables will be created at the time of method execution and destroyed once method
completes.
Local variables of a method cannot be accessed from outside of method.
Example:
class Test:
def m1(self):
a=1000
www.leelasoft.com Cell: 78-42-66-47-66 14
Leela Soft Python3 Madhu
print(a)
def m2(self):
b=2000
print(b)
t=Test()
t.m1()
t.m2()
Example:
class Test:
def m1(self):
a=1000
print(a)
def m2(self):
b=2000
print(a) #NameError: name 'a' is not defined
print(b)
t=Test()
t.m1()
t.m2()
Private variables:
Variables can be private which can be useful on many occasions. A private variable can only be
changed within a class method and not outside of the class.
Objects can hold crucial data for your application and you do not want that data to be
changeable from anywhere in the code.
An example:
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
www.leelasoft.com Cell: 78-42-66-47-66 15
Leela Soft Python3 Madhu
self.__maxspeed = 200
self.__name = "Supercar"
def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))
redcar = Car()
redcar.drive()
redcar.__maxspeed = 10 # will not change variable because its private
redcar.drive()
If we want to change the value of a private variable, a setter method is used. This is simply a
method that sets the value of a private variable.
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"
def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))
def setMaxSpeed(self, speed):
self.__maxspeed = speed
redcar = Car()
redcar.drive()
redcar.setMaxSpeed(320)
redcar.drive()
Private methods:
We create a class Car which has two methods: drive() and updateSoftware(). When a
car object is created, it will call the private methods __updateSoftware().
This function cannot be called on the object directly, only from within the class.
www.leelasoft.com Cell: 78-42-66-47-66 16
Leela Soft Python3 Madhu
class Car:
def __init__(self):
self.__updateSoftware()
def drive(self):
print('driving')
def __updateSoftware(self):
print('updating software')
redcar = Car()
redcar.drive()
# redcar.__updateSoftware() not accesible from object.
This program will output:
updating software
driving
The private attributes and methods are not really hidden, they’re renamed adding “_Car” in
the beginning of their name.
The method can actually be called using redcar._Car__updateSoftware()
Why would we create them? Because some of the private values you may want to change after
creation of the object while others may not need to be changed at all
Python Encapsulation
Type Description
public methods Accessible from anywhere
private methods Accessible only in their own class. starts with two underscores
public variables Accessible from anywhere
Accessible only in their own class or by a method if defined. starts with
private variables
two underscores
www.leelasoft.com Cell: 78-42-66-47-66 17