ECC Fall 2024 Lecture 2

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

Advanced Programming and

Algorithms

Kawtar Zerhouni, Assistant Professor - UTER MID@S - ECC

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 1


Second lecture: Advanced Object-Oriented Design

● Objectives:

• Master advanced OOP concepts like abstract classes, interfaces, multiple


inheritance, and polymorphism.

• Understand how these concepts are applied in large-scale systems through an


example around autonomous vehicles.

• Notebook available at
car_notebook

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 2


k.z
… remember these ?

● Python supports many different kinds of data


▪ Scalar, Atomic or Primitive Objects (can’t ▪ Non-scalar, Nonatomic, or Composite objects
be separated into smaller object types) (can be decomposed into other objects)
▪ Integers, floats, Booleans ▪ Strings, tuples, lists, dictionaries

● Each is an object, and every object has:


● An internal data representation (primitive or composite)
● A set of procedures for interaction with the object
● An object is an instance of a type
● 1234 is an instance of an int
● "hello" is an instance of a str
29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 3
k.z
So what are objects ?

● Objects are a form of data abstraction that encapsulate:

1) An internal representation:
● Achieved through data attributes that store the object's state and properties.

● Imagine an everyday complex object like a Car.


● The attributes of this car might include its model, color, and fuel level.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 4


k.z
So what are objects ?

● Objects are a form of data abstraction that encapsulate:

1) An internal representation

2) An interface for interacting with the object:


● Provided through methods, which are procedures or functions that define the
object's behavior.
● This interface specifies what actions can be performed on the object, while
hiding the underlying implementation details.
● For our Car object, methods could include start_engine(), drive(), and refuel()

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 5


k.z
Encapsulation: Protecting the Integrity of Objects

● Objects are a form of data abstraction


● One of the most powerful aspects of this abstraction is that it hides the
implementation details → Encapsulation

● Encapsulation ensures data integrity:


● Internal attributes are kept private to prevent unwanted or incorrect

modifications that could compromise the object’s behavior.

● If you were to manipulate the internal components of the car, such as directly
altering the engine parts or fuel lines, the car’s behavior might not work as expected.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 6


k.z
OOP: Modularity and Reusability

● Bundle data and behavior together:


● Combine data and the methods that operate on it within well-defined interfaces, making it
easier to manage and interact with complex systems.

● Divide-and-Conquer Development Approach:


● Develop and test the behavior of each class independently.
● This increased modularity reduces overall complexity by breaking down a large system
into smaller, manageable components.

● Enhanced Code Reusability with Classes:


● Many Python modules define new classes to encapsulate specific functionalities.
● Each class operates within its own environment, preventing conflicts with function names
or variables from other parts of the code.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 7


k.z
OOP: You Make the Rules!

● As the class creator, you’re the architect.

● You’re in control of what data the class holds—whether it’s a car’s speed and
fuel level or a spaceship’s crew capacity and trajectory.

● You get to define what actions can be performed on this data.


● Need the spaceship to launch into orbit? That’s a method you create.
● Want the car to accelerate or stop? You decide how it all happens!

When you’re designing a class, you’re not just writing code—you’re establishing
the rules of the universe for that object type!

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 8


k.z
Class Design vs. Instance Usage

● Creating a Class:
● This step involves defining the structure and blueprint of the class itself.
● You determine the class name, its attributes (data it holds), and methods
(what it can do).

● For example, someone had to write the code to implement the list class in Python,
specifying how a list stores elements and the operations it supports, like sorting or
reversing.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 9


k.z
Class Design vs. Instance Usage

● Creating a Class:
● This step involves defining the structure and blueprint of the class itself.
● You determine the class name, its attributes (data it holds), and methods
(what it can do).

● Using a Class:
● Once a class is defined, you can create instances (or objects) of that class.
● You can perform operations on these instances, using the methods defined
in the class.

● For example, creating a list instance with L = [1, 2] and calling len(L) to find its
length.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 10


k.z
Class design: the magical keyword

● Use the class keyword to define a new custom data type.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 11


k.z
Class design: the magical keyword

● Use the class keyword to define a new custom data type.

● Indentation is essential : all code within the class definition must be indented to
show that it belongs to the class.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 12


k.z
Class design

● Use the class keyword to define a new custom data type.

● Indentation is essential : all code within the class definition must be indented to
show that it belongs to the class.

● The word object indicates that the class inherits from Python's base object class.
● This means that the class Car is a Python object and will automatically have access
to built-in attributes and methods.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 13


k.z
Class design: Attributes

● Data Attributes:
• Represent the internal state or properties of the class.
• These can be thought of as other variables or objects that define the characteristics
of each instance.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 14


k.z
Class design: constructor

● First, define how to create an instance of a class:


• Use a special method called the __init__ constructor to initialize attributes or set up
specific configurations for the class.
• self is a reference to the current instance of the class, allowing you to assign attributes to it.

Without self, you are just creating regular variables!


29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 15
k.z
A Class is Just a Blueprint

● When we define a class, we’re not creating an actual, tangible object yet.
● Instead, we’re building a blueprint or a template that outlines what the
object should look like and how it should behave.
● It’s a plan, a definition, but it doesn’t come to life until we use that
blueprint to create an instance.

The class itself is just an abstract representation—like an architect’s design


for a house before any bricks are laid or walls are built.”

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 16


k.z
Class Design vs. Instance Usage

● Creating an instance of the class:


• Use the class name followed by parentheses to create a new object.

● Data attributes of an instance are called instance variables:


• Instance variables are defined inside the __init__ constructor using self.
• Each instance has its own set of variables, accessed using dot notation

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 17


k.z
Class design: Methods

● Methods (Procedural Attributes):


• Functions that are specifically designed to operate on instances of the class.
• Define how you can interact with or manipulate the object's internal state.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 18


k.z
Class design: Methods

● Methods (Procedural Attributes):


• Functions that are specifically designed to operate on instances of the class.
• Define how you can interact with or manipulate the object's internal state.

Use it to refer to the object I call this method on

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 19


k.z
Class design: Methods

● Methods (Procedural Attributes):


• Functions that are specifically designed to operate on instances of the class.
• Define how you can interact with or manipulate the object's internal state.

Use it to refer to the object I call this method on

Dot notation to access Color of self


29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 20
k.z
Class design: Methods

● Methods (Procedural Attributes):


• Functions that are specifically designed to operate on instances of the class.
• Define how you can interact with or manipulate the object's internal state.

Use it to refer to the object I call this method on


Other than self and dot
notation, methods behave
just like functions (take
params, do operations,
return)

Dot notation to access Color of self


29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 21
k.z
Class Design vs. Instance Usage

● Call the method


● using dot notation: object_name.method_name(parameters)

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 22


k.z
Class Design vs. Instance Usage

● Call the method


● using dot notation: object_name.method_name(parameters)

Object to call Parameters not


method on including self
Name of the method

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 23


k.z
Class Design vs. Instance Usage

● Conventional way

→ Equivalent to
Parameters including an
Name of the
object to call the method on
class Name of the method

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 24


k.z
Getter and setter methods

● Getters and setters are special methods in OOP that provide controlled access to an
object's attributes.
● They encapsulate the internal state of an object, allowing safe interactions with its
data while maintaining the flexibility to make internal changes without affecting
external code.

● Why Use Getters and Setters?


● Encapsulation and Data Hiding.

● Validation and Error Checking

● Logging and Debugging

● Read-Only or Write-Only Attributes

● Consistent Interface

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 25


k.z
Getter and setter methods

Getter method
allows external code
to read the value of
speed

Setter method allows


controlled modification
of the attribute

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 26


k.z
Getter and setter methods

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 27


k.z
Getter and setter methods

Applied without setter


++ simple and works well when you don’t need additional checks or logic.
-- No way to ensure that speed is set to a reasonable value

Using a setter
++ allows to include validation logic
-- Slightly More Complex

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 28


k.z
Getter and setter methods

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 29


k.z
Getter and setter methods

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 30


k.z
More abstraction : Inheritance

● Inheritance is a fundamental concept in OOP that allows a class (known as


the child class) to inherit attributes and methods from another class
(known as the parent class).

● This mechanism helps in building hierarchies and relationships between


classes, making the code more organized, modular, and reusable.

When using inheritance, we define a new class that is based on an existing


class, allowing us to extend or modify its functionality without rewriting code.

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 31


k.z
Inheritance in OOP

● Vehicle class as the parent class and specific vehicle types like Car and Truck as
child classes.

● Defining the Parent Class

29/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 32


k.z
Inheritance in OOP

● Vehicle class as the parent class and specific vehicle types like Car and Truck as
child classes.

● Defining a child Class

Parent class

super() is used to call


methods or access
attributes from the
parent class in a child
class.

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 33


k.z
Inheritance in OOP

● Vehicle class as the parent class and specific vehicle types like Car and Truck as
child classes.

● Defining a child Class

Define new
attributes

Define a new
method

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 34


k.z
Inheritance in OOP

● Vehicle class as the parent class and specific vehicle types like Car and Truck as
child classes.

● Defining a second child Class

Define a new
attribute

Define a new
method

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 35


k.z
Inheritance in OOP

• Creating Instances

• Using Methods:

Method from superclass Methods from


subclasses

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 36


k.z
Advanced Topics

● Multiple Inheritance and Method Resolution Order (MRO)


● Multiple inheritance and MRO are advanced concepts in OOP that allow
classes to inherit from more than one parent class.

● These features add flexibility and complexity to class design, enabling


sophisticated modeling of relationships between classes.
.

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 37


k.z
Multiple inheritance and MRO

• Multiple Inheritance allows a class to inherit attributes and methods from more than
one parent class.
• This is in contrast to single inheritance, where a class can inherit from only one
parent class.

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 38


k.z
Multiple inheritance and MRO

• Multiple Inheritance allows a class to inherit attributes and methods from more than
one parent class.
• This is in contrast to single inheritance, where a class can inherit from only one
parent class.
HybridCar class inherits all the attributes and methods
from both Vehicle and Electric

defines a new
method
30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 39
k.z
Multiple inheritance and MRO

• Creating an Instance of the new child class

• Using Methods

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 40


k.z
Multiple inheritance and MRO

• The Method Resolution Order (MRO) is a core concept in multiple inheritance that
defines the order in which classes are checked when a method is called on an object.

• It determines how Python searches through parent classes to resolve method or


attribute names.

• Check the MRO

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 41


k.z
Multiple inheritance and MRO

• Check the MRO (thrivia)

An attribute that returns a tuple of classes


→ best suited for inspection and debugging.

method that returns a list of classes


→ easier manipulation and iteration

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 42


k.z
Multiple inheritance and MRO

● Check the MRO


1. HybridCar (the child class itself)

2. Vehicle (first parent class)

3. Electric (second parent class)

4. object (base class of all classes in Python)

First parent Second parent

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 43


k.z
Multiple inheritance and MRO

• Python first looks for the charge_battery() method in the HybridCar class.
• It is not found in HybridCar, so it moves to the next class in the MRO: Vehicle.
• The charge_battery() method is not found in Vehicle, so it moves to the next class
in the MRO: Electric.
• The charge_battery() method is found in Electric and executed, resulting in the
output: Battery is charging....
30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 44
k.z
Advanced Topics

● Polymorphism and Method Overriding


● Polymorphism is one of the core principles of OOP along with inheritance,
encapsulation, and abstraction.
● It allows objects of different classes to be treated as instances of the
same class through a common interface, enabling flexibility and reusability
in code design.

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 45


k.z
Polymorphism and Method Overriding

● The term polymorphism comes from the Greek words "poly," meaning many, and
"morph," meaning form.

● It refers to the ability of different classes to be used interchangeably through a


shared interface or base class

This means that you can call the same method on different types of objects, and each object
will respond in its own way, depending on its class definition.

● Method overriding occurs when a child class provides a specific implementation for a
method that is already defined in its parent class.

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 46


k.z
Polymorphism and Method Overriding

● Let’s take the following example


● The Superclass Vehicle

● This method will be overridden by each subclass to provide specific behaviors.

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 47


k.z
Polymorphism and Method Overriding

● Overriding Methods in Subclasses

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 48


k.z
Polymorphism and Method Overriding

● Overriding Methods in Subclasses

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 49


k.z
Polymorphism and Method Overriding

● Overriding Methods in Subclasses

- Overrides the start_engine() method

- Includes a check for


self.power_mode to determine if the
car should start using electric power
or gasoline.

- Adds a new method


switch_power_mode() to switch
between electric and gasoline
modes.
30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 50
k.z
Polymorphism and Method Overriding

● Demonstrating Polymorphism

same method

Different outputs

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 51


k.z
Polymorphism and Method Overriding

● Demonstrating Polymorphism

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 52


k.z
Polymorphism and Method Overriding

● Demonstrating Polymorphism

same method

it is easy to extend functionality without modifying existing code

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 53


k.z
Even more Advanced Topics

● Abstract Classes
● An abstract class is a class that cannot be instantiated directly.
● It serves as a blueprint for other classes.
● Abstract classes are designed to be inherited by subclasses that provide
concrete implementations of its abstract methods.

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 54


k.z
Abstract classes

● Cannot be Instantiated Directly:


● Abstract classes cannot be instantiated on their own.
● This means you cannot create an object of an abstract class directly.

● Contain Abstract Methods:


● An abstract method is a method that is declared but does not contain any implementation (i.e., no
method body).
● Subclasses that inherit from the abstract class are required to provide implementations for all its
abstract methods.

● Can Have Concrete Methods:


● Abstract classes can also contain concrete methods (methods with complete implementations).
● This allows them to provide default behavior that can be shared across subclasses, while still
enforcing certain methods to be implemented in subclasses.
30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 55
k.z
Abstract classes

● Creating Abstract Classes

● Use the abc (Abstract Base Classes) module.


● It provides the ABC class and @abstractmethod decorator to define abstract classes and methods.

Vehicle is defined as an abstract class by


inheriting from ABC

abstract method
decorated, every subclass
must implement this
method.
concrete method that is
shared by all subclasses.
30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 56
k.z
Abstract classes

● Inheritance:

● Both GasolineCar and ElectricCar inherit from Vehicle and provide specific implementations
of the abstract method start_engine().

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 57


k.z
Abstract classes

● You cannot create an instance of the Vehicle class itself, as it is an abstract class !

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 58


k.z
Abstract classes

● You can create instances of its subclasses (GasolineCar and ElectricCar) and call their
respective methods.

Abstract method
different behavior

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 59


k.z
Abstract classes

● You can create instances of its subclasses (GasolineCar and ElectricCar) and call their
respective methods.

Concrete method

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 60


k.z
Advanced Programming and
Algorithms

Kawtar Zerhouni, Assistant Professor - UTER MID@S - ECC

30/09/2024 ECC – Fall 2024 – Advanced Programming and Algorithms 61

You might also like