Professional Documents
Culture Documents
Unit 3
Unit 3
PYTHON
PROGRAMMING
Course Code : GR20A2068
Object-oriented programming
Paradigms
Paradigm can also be termed as a method to solve some problems or
do some tasks. A programming paradigm is an approach to solving
the problem using some programming language or also we can say it
is a method to solve a problem using tools and techniques that are
available to us following some approach.
Procedural programming:
A step-by-step procedure is followed sequentially to solve a problem
Class
Objects
Polymorphism
Encapsulation
Inheritance
Python is a multi-paradigm programming language. It supports different
programming approaches.
Class parrot
pass
The class keyword is used to create an empty class called Parrot. We create instances from classes. A unique
object formed from a certain class is referred to as an instance.
class ClassName:
#statement1
#statementN
Objects
The object is an entity that has a state and behavior associated with it. It may be any
real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings,
floating-point numbers, even arrays, and dictionaries, are all objects.
• OBJECT
• p1 = MyClass()
print(p1.x)
• O/p: 5
Object declaration
• class MyClass:
mem = 5
• Obj=MyClass
• Print( obj.mem)
_init_ a built in function
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name, +self.age)
p1 = Person("John", 36)
p1.myfunc()
Self parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the
class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function
in the class:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
DELETE
A static method is also a method that is bound to the class and not the
object of the class.
A static method can’t access or modify the class state.
It is present in a class because it makes sense for the method to be
present in class.
Example 1: Create a static method using staticmethod()
class Mathematics:
OUTPUT:
The sum is 15
Class Method
The class method decorator is a built-in function decorator that is an expression
that getsevaluated after your function is defined. The result of that evaluation
shadows your function definition.
A class method receives the class as an implicit first argument, just like an
instance method receives the instance
•A class method is a method that is bound to the class and not the object
of the class.
•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.
•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 apply to all
the instances.
def show(self):
print(self.name + "'s age is: " + str(self.age))
@classmethod
def calculate_age(cls, name, birth_year):
# calculate age an set it as a age
# return new object
return cls(name, date.today().year - birth_year)
Class method vs Static Method
• A class method takes cls as the first parameter while a static method needs
no specific parameters.
• A class method can access or modify the class state while a static method
can’t access or modify it.
• In general, static methods know nothing about the 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 a
parameter.
• We use @classmethod decorator in python to create a class method and
we use @staticmethod decorator to create a static method in python.
Inheritance
Inheritance is the capability of one class to derive or inherit the properties from
another class. The class that derives properties is called the derived class or child
class and the class from which the properties are being derived is called the base
class or parent class. The benefits of inheritance are:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
OUTPUT:
def dance(self):
return "{} is now dancing".format(self.name)
Blu sings 'Happy'
# instantiate the object Blu is now dancing
blu = Parrot("Blu", 10)
print("Swim faster")
# child class
OUTPUT:
class Penguin(Bird):
Bird is ready
def __init__(self):
Penguin is ready
# call super() function Penguin
Swim faster
super().__init__() Run faster
print("Penguin is ready")
In the above program, we created two classes i.e. Bird
(parent class) and Penguin (child class). The child class
inherits the functions of a parent class. We can see this
from the swim() method.
def sell(self):
print("Selling Price:
{}".format(self.__maxprice))
OUTPUT:
def setMaxPrice(self, price):
self.__maxprice = price Selling Price: 900
Selling Price: 900
Selling Price: 1000
c = Computer()
c.sell()
c.__maxprice = 1000
c.sell()
• Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for
multiple forms (data types).
Polymorphism simply means having many forms.
Using Polymorphism in Python (Example)
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
OUTPUT:
def __init__(self):
# body of the 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("John", 101)
emp2 = Employee("David", 102) OUTPUT:
# accessing display() method to print employee 1 information ID: 101
emp1.display() Name: John
ID: 102
# accessing display() method to print employee 2 information
Name: David
emp2.display()
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.
When we do not include the constructor in the class or forget to declare it, then that
becomes the default constructor. It does not perform any task but initializes the objects.
Consider the following example.
Example
class Student:
roll_num = 101
OUTPUT:
name = "Joseph"
101 Joseph
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate the
value or the constructor that has only self as an argument. Consider the following
example.
Example
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")
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self. Consider the following example.
Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
Output:
class Calculator:
sum = Calculator.add_numbers(5, 7)
print('Sum:', sum)
# Output: Sum: 12
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined
operational meaning. For example, operator + is used to add two integers as well as join
two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int
class and str class. You might have noticed that the same built-in operator or function
shows different behavior for objects of different classes, this is called Operator
Overloading.
Example:
print (14 + 32)
# Now, we will concatenate the two strings OUTPUT:
print (“Gokaraju" + “Rangaraju")
46
# We will check the product of two numbers GokarajuRangaraju
print (23 * 14) 322
XYZXYZXYZ
# Here, we will try to repeat the String
print ("X Y Z " * 3)
How to Overload the Operators in Python?
Suppose the user has two objects which are the physical representation of a user-
defined data type class. The user has to add two objects using the "+" operator, and
it gives an error. This is because the compiler does not know how to add two
objects. So, the user has to define the function for using the operator, and that
process is known as "operator overloading". The user can overload all the existing
operators by they cannot create any new operator. Python provides some special
functions, or we can say magic functions for performing operator overloading, which
is automatically invoked when it is associated with that operator. Such as, when the
user uses the "+" operator, the magic function __add__ will automatically invoke in
the command where the "+" operator will be defined.
Program 2: defining Overloading operator in another object
Python program for defining the overloading operator inside another object.
Example:
class complex_1:
def __init__(self, X, Y):
self.X = X
self.Y = Y
# Parent class
class Parent :
# Constructor
# Variables of Parent class
# Methods
...
...
...
Example: # creating object of child class
obj = Child()
# parent class
class Parent: # calling parent class m1() method
obj.m1()
# parent class method
def m1(self): # calling child class m2() method
print('Parent Class Method obj.m2()
called...')
class A :
# variables of class A
# methods of class A
...
...
class B :
# by using "obj" we can access member's of class A.
obj = A()
# variables of class B
In the above figure Classes are represented as boxes with the # methods of class B
class name Composite and Component representing Has-A
relation between both of them. ...
...
# composite class instance method
Example: def m2(self):
class Parent():
def show(self):
print("Inside Parent")
class Child(Parent):
def show(self):
Multiple Inheritance
When a class is derived from more than one base class it is
called multiple Inheritance. The derived class inherits all the
features of the base case.
Syntax:
Class Base1:
Body of the class
Class Base2:
Body of the class
class Base2:
pass
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
import threading
def print_hello(n):
print("Hello, how old are you ", n)
t1 = threading.Thread( target = print_hello, args =(18, ))
3. Start a new thread:
To start a thread in Python multithreading, call the thread class's object. The start() method can be called once for
each thread object; otherwise, it throws an exception error.
Syntax:
t1.start()
t2.start()
4. Join method:
It is a join() method used in the thread class to halt the main thread's execution and waits till the complete
execution of the thread object. When the thread object is completed, it starts the execution of the main thread in
Python.
Joinmethod.py
import threading
def print_hello(n):
Print("Hello, how old are you? ", n)
T1 = threading.Thread( target = print_hello, args = (20, ))
T1.start()
T1.join()
Print("Thank you")
Output:
Hello, how old are you? 20
Thank you
5. Synchronizing Threads in Python