Programming For AI-
OOP Concepts
Muhammad Ahsan Raees
Procedural Oriented Approach
• A computer program describes procedure of performing certain task by
writing a series of instructions in a logical order.
• Logic of a more complex program is broken down into smaller but
independent and reusable blocks of statements called functions.
• Prominent problems related to procedural approach are as follows
• Its top-down approach makes the program difficult to maintain.
• It uses a lot of global data items, which is undesired. Too many global data items
would increase memory overhead.
• It gives more importance to process and doesn't consider data of same importance
and takes it for granted, thereby it moves freely through the program.
• Movement of data across functions is unrestricted. In real-life scenario where there is
unambiguous association of a function with data it is expected to process.
Python - OOP Concepts
Attributes
• Name, class, subjects, marks, etc., of student
• Name, designation, department, salary, etc., of employee
• Invoice number, customer, product code and name, price and
quantity, etc., in an invoice
• Registration number, owner, company, brand, horsepower, speed,
etc., of car
Behavior
• Compute percentage of student's marks
• Calculate incentives payable to employee
• Apply GST to invoice value
• Measure speed of car
Principles of OOPs Concepts
Class & Object
• Class
• A class is an user-defined prototype for an object that defines a set of attributes
that characterize any object of the class.
• The attributes are data members (class variables and instance variables) and
methods, accessed via dot notation.
• Object
• An object refers to an instance of a certain class.
• For example, an object named obj that belongs to a class Circle is an instance of
that class.
• 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.
Creating Classes in Python
• The class keyword is used to create a new class in Python. The name
of the class immediately follows the keyword class followed by a
colon as shown below
class ClassName:
class_suite
Python - Constructors
• Python constructor is an instance method in a class, that is automatically called
whenever a new object of the class is created.
• The constructor's role is to assign value to instance variables as soon as the object is
declared.
• Python uses a special method called __init__() to initialize the instance variables for
the object, as soon as it is declared.
• Creating a constructor in Python
def __init__(self, parameters):
#initialize instance variables
• The __init__() method as well as any instance method in a class has a mandatory
parameter, self. However, you can give any name to the first parameter, not
necessarily self.
Creating Objects of Classes in
Python
• To create instances of a class, you call the class using class name and
pass in whatever arguments its __init__ method accepts.
Accessing Attributes of Objects in
Python
• You access the object's attributes using the dot operator with object.
Class variable would be accessed using class name as follows
[Link]()
[Link]()
print ("Total Employee %d" % [Link])
Example
• Write a Python program to • class circle:
create a class representing a • def __init__(self, r):
Circle. Include methods to • self.r=r
•
calculate its area and perimeter. def area(self):
• return 3.14*self.r*self.r
• def prem(self):
• return 2*3.14*self.r
• R=int(input("enter the radius
of circle"))
• c=circle(R)
• print("Area",[Link]())
• print("premiter",[Link]())
Inheritance
• What is Inheritance in Python?
• Inheritance is one of the most important features of object-oriented programming languages like
Python.
• It is used to inherit the properties and behaviours of one class to another.
• The class that inherits another class is called a child class and the class that gets inherited is called a
base class or parent class.
• If you have to design a new class whose most of the attributes are already well defined in an
existing class, then why redefine them?
• Inheritance allows capabilities of existing class to be reused and if required extended to design a
new class.
• Inheritance comes into picture when a new class possesses 'IS A' relationship with an existing class.
• For example, Car IS a vehicle, Bus IS a vehicle, Bike IS also a vehicle. Here, Vehicle is the parent
class, whereas car, bus and bike are the child classes.
Creating a Parent Class: Syntax
• The class whose attributes and methods are inherited is called as
parent class. It is defined just like other classes i.e. using the class
keyword.
• Syntax
class ParentClassName:
{class body}
Creating a Child Class
• Classes that inherit from base classes are declared similarly to their
parent class, however, we need to provide the name of parent classes
within the parentheses.
• Syntax
class SubClassName (ParentClass1[, ParentClass2, ...]):
{sub class body}
class Person:
Example def __init__(self, name, age):
[Link] = name
Create a parent class called Person with [Link] = age
attributes name and age. Add a method
def display_details(self):
to display these details. Create a child
print(f"Name: {[Link]}, Age:
class called Student that inherits from {[Link]}")
the Person class and adds an attribute
class Student(Person):
student_id. Add a method to display the
def __init__(self, name, age,
student's details, including their ID. student_id):
super().__init__(name, age)
self.student_id = student_id
def display_details(self):
super().display_details()
print(f"Student ID:
{self.student_id}")
student = Student("Ahsan", 20, "S12345")
student.display_details()
Polymorphism
• What is Polymorphism in Python?
• The term polymorphism refers to a function or method taking
different forms in different contexts.
• Since Python is a dynamically typed language, polymorphism in
Python is very easily implemented.
• If a method in a parent class is overridden with different business
logic in its different child classes, the base class method is a
polymorphic method.
Syntax
class ParentClass:
def method(self):
print("This is the parent class method.")
class ChildClass(ParentClass):
def method(self):
print("This is the child class method.")
# Example of polymorphism
obj1 = ParentClass()
obj2 = ChildClass()
[Link]() # Calls the ParentClass method
[Link]() # Calls the ChildClass method (overridden)
Method Overriding in Python
• In method overriding, a method defined inside a subclass has the
same name as a method in its superclass but implements a different
functionality.
Example
from abc import ABC, abstractmethod class rectangle(shape):
class shape(ABC):
def draw(self):
@abstractmethod
def draw(self): super().draw()
"Abstract method" print ("Draw a rectangle")
return return
class circle(shape):
shapes = [circle(), rectangle()]
def draw(self):
super().draw() for shp in shapes:
print ("Draw a circle") [Link]()
return
Example
Create a class called Person with attributes,name and age.
Include a method to display the details of a person. Then,
create a class called Employee that inherits from Person and
adds an attribute salary. Override the method to display the
details of the employee, including their salary. Finally, create
an instance of the Employee class and demonstrate
polymorphism by calling the overridden method.
• class person:
• def __init__(self,name,age):
• [Link]=name
• [Link]=age
• def display_details(self):
• print(f"Name: {[Link]}")
• print(f"Age: {[Link]}")
• class employee(person):
• def __init__(self,name,age,salary):
• super().__init__(name,age)
• [Link]=salary
• def display_details(self):
• super().display_details()
• print(f"Salary: {[Link]}")
• e=employee("Ahsan Raees",30,50000)
Quiz
• Create a class called Vehicle with the following attributes: make,
model, and year. Include methods to display vehicle details. Then,
create a class Car that inherits from Vehicle and adds an attribute
color. Add a method to display the color of the car. Finally, create an
instance of the Car class and demonstrate polymorphism by
overriding the display_details method to display both the vehicle and
car details.
• class vehicle:
• def __init__(self,make,model,year):
Solution
•
•
[Link]=make
[Link]=model
• [Link]=year
• def display_details(self):
• print(f"Make: {[Link]}")
• print(f"Model: {[Link]}")
• print(f"Year: {[Link]}")
• class car(vehicle):
• def __init__(self,make,model,year,color):
• super().__init__(make,model,year)
• [Link]=color
• def display_details(self):
• super().display_details()
• print(f"Color: {[Link]}")
• c=car("Toyota","Camry",2022,"Red")
Thank You