Unit-4 OOP 26june24
Unit-4 OOP 26june24
• Web Development,
• Game Development,
• Scientific and Numeric Applications,
• Artificial Intelligence and Machine Learning,
• Software Development,
• Enterprise-level/Business Applications,
• Education programs and training courses,
• Language Development etc.
Python class:
•Classes are created by keyword class.
•Attributes are the variables that belong to a class.
•Attributes can be accessed using the dot (.) operator.
• Classes define functions called methods, which identify the behaviors and
actions that an object created from the class can perform with its data.
• Methods can be accessed using dot(.) operator.
• We can access the class attribute via instances of the class or via
the class name: object_name.class_attribute or class_name.class_attribute
p1=Person(“John”, 30)
print(p1.name)
print(p2.age)
Output:
John
30
Difference b/w class & instance attributes
• Class attributes are variables that are associated with a class rather
than with instances (objects) of that class.
• Class attributes are shared among all instances of a class and are
defined within the class itself.
• Instance attributes are variables that belong to an instance of a
class.
• Each instance attribute is specific to a particular object created from
that class.
• These attributes define the characteristics or properties of individual
objects.
Aspect Class Attributes Instance Attributes
Defined within the class block but Defined within methods, typically
Definition outside of methods the __init__ constructor
Shared among all instances of the
Scope class Specific to each instance of the class
Storage
Location Stored in the class namespace. Stored in the instance namespace.
def print_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
Output:
print(f"Job Title: {self.job_title}")
print(f"Salary: {self.salary}") Name: John Smith
Age: 30
employee1 = Employee("John Smith", 30, "Software Engineer“, 50000) Job Title: Software Engineer
employee1.print_info() Salary: 50000
Built-in Objects
• First line is constructing an object of type list,
stuff = list()
• Second and third lines are calling the append()
stuff.append('python') method.
• Fourth line is calling the sort() method, and
stuff.append('chuck')
• the fifth line is retrieving the item at position 0.
stuff.sort() • The sixth line is calling the __getitem__()
print (stuff[0]) method in the stuff list with a parameter of zero.
• The seventh line is a way of retrieving the 0th
print (stuff.__getitem__(0)) item in the list.
print (list.__getitem__(stuff,0)) • The last three lines of the program are
completely equivalent.
Fundamental Principles of object-oriented
programming
• Class
• Objects
• Inheritance
• Polymorphism
• Data Abstraction
• Encapsulation
Fundamental Principles of object-oriented programming (Contd.)
o Class
A class is a collection of objects. A class contains the blueprints or the prototype from
which the objects are being created. It is a logical entity that contains some attributes and
methods.
o Object
The object is an entity that has a state and behaviour 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.
An object consists of:
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
Fundamental Principles of object-oriented programming (Contd.)
o Inheritance
• Inheritance allows a class to inherit the properties and methods of another
class called the parent class, the base class, or the super-class.
• The class that inherits is called the child class or sub-class.
• It helps to avoid duplication of codes by allowing code reuse as we need not
define the same methods and properties present in a super-class in the sub-
classes again.
• The sub-class can simply inherit them.
Fundamental Principles of object-oriented programming (Contd.)
o Polymorphism
• The word polymorphism means to have many forms. So, by using
polymorphism, you can add different meanings to a single component.
• There are two types of polymorphism:
Run-time polymorphism
Compile-time polymorphism
Fundamental Principles of object-oriented programming (Contd.)
Method Overloading
Methods overloading is a type of compile-time polymorphism using which you can define
various functions with the same name but different numbers of arguments. The function call is
resolved at compile time, so it's a type of compile-time polymorphism.
Example:
You can create a function “add”. Now, when you pass two integers to this function, it will
return their sum, while on passing two strings, it will return their concatenation.
So, the same function acts differently depending on the input data type.
• Method Overriding
• Method Overriding is a type of run-time polymorphism. It allows overriding a parent class’s
method by a child class. Overriding means that a child class provides a new implementation
of the same method it inherits from the parent class.
• These function calls are resolved at run-time, so it's a type of runtime polymorphism.
Example:
• You can have a parent class called “Shape” with a method named “findArea” that calculates
and returns the area of the shape. Several sub-classes inherit from the “Shape,” like Square,
Circle, Rectangle, etc. Each of them will define the function “findArea” in its way, thus
overriding the function.
Fundamental Principles of object-oriented programming (Contd.)
o Data Abstraction
• It hides unnecessary code details from the user. When we do not want to give out sensitive
parts of our code implementation to users.
Example: when you toggle a switch, it simply turns on or off the lights. Here, we only know the
functionality of the switch, but we don’t know its internal implementation, like how it works.
o Encapsulation
o It describes the idea of wrapping data and the methods that work on data within one unit.
This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can only
be changed by an object’s method. Those types of variables are known as private variables.
o A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.
Fundamental Principles of object-oriented programming (Contd.)
Encapsulation (Contd..)
Example:
• You can have some private variables in a class that you can't access outside the class for
security reasons. Now, to read or change the value of this variable, you can define public
functions in the class which will perform the read or writes operations.
Note:
• Both are nearly synonyms because data abstraction is achieved through encapsulation.
Inheritance
• One of the core concepts in object-oriented programming (OOP)
languages is inheritance.
• It is a mechanism that allows us to create a hierarchy of classes that
share a set of properties and methods.
• When one class inherits from another, it automatically takes on all the
attributes and methods of the first class but is also free to define new
attributes and methods of its own.
• The original class is called the parent class or base class or super class,
and the new class is the child class or derived class or sub class.
Advantages of Inheritance
• It represents real-world relationships well.
• It provides the reusability of a code. Repeating the same
code again in another class is avoided as well, more features
can be added without modifying existing ones.
• 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.
• Inheritance offers a simple, understandable model structure.
• Development and maintenance expenses are comparatively
reduced.
Python Inheritance Syntax
class BaseClass:
{Body}
class DerivedClass (BaseClass):
{Body}
- An object of derived class can access the base class methods also.
- But an object of base class cannot access derived class methods.
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Derived class
class Car(Vehicle):
def car_info(self):
print('Inside Car class') Output
Inside Vehicle class
# Create object of Car Inside Car class
car = Car()
• To do this, the __init__() method for a child class needs help from its
parent class.
• Example:
• Let us model the Electric Car. It is a specific type of a car.
• Hence, we can have a base class as Car and a derived-class as
Electric_Car.
class Car:
"""A simple attempt to represent a car.""" def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
def __init__(self, manufacturer, model, year): self.odometer_reading += miles
"""Initialize attributes to describe a car."""
self.manufacturer = manufacturer class ElectricCar(Car):
self.model = model """Represent aspects of a car, specific to electric
self.year = year vehicles."""
self.odometer_reading = 0
def __init__(self, manufacturer, model, year):
def get_descriptive_name(self): """Initialize attributes of the parent class."""
"""Return a neatly formatted descriptive name.""" super().__init__(manufacturer, model, year)
long_name = f"{self.year} {self.manufacturer}
{self.model}"
return long_name.title() my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on
it.")
class A:
Whenever we change the behaviour of def __init__(self, a):
the existing operator through operator self.a = a
overloading, we have to redefine the # adding two objects
special function that is invoked def __add__(self, o):
automatically when the operator is used return self.a + o.a
with the objects. ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")
print(ob1 + ob2)
print(ob3 + ob4)
Complex number addition
• Create a class called complex, define a parameterized constructor to initialize real and
imaginary parts.
• Overload the + operator to add 2 given complex numbers and assign it to the third complex
number.
Overloading the less-than-operator <
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Alice", 20)
p2 = Person("Bob", 30)
b1=Batsman('Rahul',50,6000)
b1.avg()
print("Average runs scored by ",b1.name,":",b1.avg)
Example
• Develop a Python program to create a class Time with data
members – hours and minutes. Include the following methods:
• A parameterized constructor to set values to the hours and
minutes,
• A method ‘accept’ to accept the values for the members from the
user.
• Overload the + operator to add two given times. Ex. If Time1 has
hours=11 minutes=50 and Time2 has hours =4 minutes =40, then
Time3 should be hours=16 minutes=30
• A method to display the all the time objects.
• Create two objects of class Time and assign the sum of these two
objects to a third object.