0% found this document useful (0 votes)
16 views27 pages

Oop 6

The document introduces Object-Oriented Programming (OOP), explaining its core principles such as encapsulation, inheritance, polymorphism, and abstraction. It emphasizes the benefits of OOP, including modularity, reusability, scalability, and flexibility, while detailing key concepts like classes, objects, and methods. Additionally, it covers the significance of encapsulation in data protection and the roles of getters and setters in managing access to object attributes.

Uploaded by

Yeabkab Tibebu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views27 pages

Oop 6

The document introduces Object-Oriented Programming (OOP), explaining its core principles such as encapsulation, inheritance, polymorphism, and abstraction. It emphasizes the benefits of OOP, including modularity, reusability, scalability, and flexibility, while detailing key concepts like classes, objects, and methods. Additionally, it covers the significance of encapsulation in data protection and the roles of getters and setters in managing access to object attributes.

Uploaded by

Yeabkab Tibebu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

CH-6

BY : Habtamu Girum
email: Email Address
linkedin : Linkedin
Introduction to OOP

What is OOP? Object-Oriented Programming is a programming paradigm that organizes code around "objects" rather
than functions or procedures. Objects are instances of classes, which act as blueprints defining the properties
(attributes) and behaviors (methods) of those objects.

blueprint objects
Why OOP?
Modularity: OOP groups related data and functions together, making code easier to
understand and maintain.
Reusability: You can reuse code through inheritance, reducing redundancy.
Scalability: Large projects are easier to manage with OOP because of its structured
approach.
Flexibility: Polymorphism allows objects to be treated uniformly, even if they behave
differently.
Classes and Objects

Class: A class is a template or blueprint for creating objects. It defines attributes (data) and methods
(functions) that the objects will have.
Object: An object is an instance of a class, created from the class blueprint. Each object can have its
own values for the class’s attributes.
Syntax:
Class definition: class ClassName:
Object creation: obj = ClassName()
Key Points:
The __init__ method (constructor) initializes an object’s attributes.
The self parameter refers to the current object, allowing access to its attributes and methods.
Example

class define and create object


class ClassName:
pass
obj_name = ClassName()
__init__(self, attribute)

The __init__ method in Python is a constructor,


automatically called when an object is created
from a class. Its primary role is to initialize the
object's attributes. Every time a new instance
of a class is created, the __init__ method is
invoked for that specific object.

The __str__ method in Python is a


special method used to define a
string representation of an object.
It's called when the built-in str()
function or the print() function is
used on an instance of a class.
instance attribute and class attribute

A class attribute is a property that belongs to the class itself and is shared
among all instances of that class. It is defined within the class body and
accessed using the class name. Class attributes are used to maintain
values that remain the same for all objects created from the class.

An instance attribute is a property that is unique to each individual


object (instance) created from the class. It is defined within the
methods of the class and accessed using the self keyword. Instance
attributes represent the specific characteristics or state of each
object.
EXAMPLE
Core OOP Concepts

OOP revolves around four key principles:


1.Encapsulation: Bundling data (attributes) and methods that operate on that data into a single
unit (class), while restricting access to some components to protect data integrity. Think of a
capsule protecting its contents.
2.Inheritance: Allows a class (child) to inherit attributes and methods from another class
(parent), promoting code reuse. Imagine a child inheriting traits from a parent.
3.Polymorphism: Enables objects of different classes to be treated as objects of a common
parent class, with each class implementing shared methods differently. Picture different
animals making their unique sounds when asked to "speak."
4.Abstraction: Hides complex implementation details and exposes only the necessary
functionality, simplifying interaction with objects. Think of a TV remote—you press buttons
without knowing the internal circuits.
Encapsulation is an OOP principle that involves bundling the data (attributes) and methods
(functions) that operate on that data into a single unit, typically a class, while restricting
direct access to some of the object’s components. It’s about protecting an object’s internal
state and exposing only what is necessary through a controlled interface.
Why Encapsulation?
Data Protection: Prevents unauthorized or unintended access to an object’s data,
reducing the risk of errors.
Modularity: Groups related data and behavior together, making code easier to
understand and maintain.
Flexibility: Allows internal implementation changes without affecting external code, as
long as the interface remains consistent.
Abstraction: Hides complex details, exposing only a simple interface to the user.
Key Components
private
public
protected
Data Hiding:
Encapsulation restricts direct access to an object’s attributes to prevent misuse or
accidental modification.
In Python, this is achieved using:
Private Attributes: Denoted by double underscores (__attribute), which triggers
name mangling to make attributes harder to access directly.
Protected Attributes: Denoted by a single underscore (_attribute), a convention
indicating that the attribute should not be accessed directly, though it’s still
accessible.
Public Attributes: Denoted by self.attribute it is fully accessible and form the
public interface.

Getters and Setters: The @property decorator allows you to define methods that act like
attributes, providing controlled read/write access with validation or logic.
Example
Encapsulation, getter, and setter methods work together to
protect data within a class by controlling access to and
modification of its internal variables.
Getter methods are used to retrieve values, while setter
methods allow controlled modification and validation of
those values.
Getter and Setter Methods:
Getter:
A public method (or property in some languages) that allows external access to the value of a class's
internal variable (field).
It returns the current value of the variable.
It can also be used to perform calculations or transformations on the value before returning it.
Setter:
A public method (or property) that allows modification of the value of a class's internal variable.
It takes a new value as input and assigns it to the variable.
Validation: Setters are often used to include validation logic, ensuring that only valid values are
assigned to the variable.
In this example, _value is Example @property setter and getter
considered a protected attribute
(indicated by the single
underscore prefix).
The @property decorator is used
to define the getter, setter, and
deleter methods for the value
attribute.
This allows controlled access and
modification of the underlying
_value attribute, enabling
encapsulation and data
validation.
@<property_name>.setter
Inheritance:

Inheritance allows a class (child/subclass) to inherit attributes and methods from


another class (parent/superclass). This promotes code reuse and establishes a
hierarchical relationship.
Syntax: class ChildClass(ParentClass):
Key Points:
The child class can override parent methods or add new ones.
Use super() to call parent class methods (e.g., in __init__).
Python supports multiple inheritance (inheriting from multiple parents)
Example
Polymorphism
Definition: Polymorphism allows objects of different classes to be treated as objects of a common parent class,
with each class implementing shared methods in its own way. It’s about flexibility and interchangeability.
How It Works: A parent class defines a method (often abstract), and child classes override it with their specific
implementations.

Two types of Polymorphism :


❑ Compile-time Polymorphism
❑ Run-time Polymorphism
Compile-time polymorphism, also known as static polymorphism, is resolved during the
compilation phase of the program. The method or operation to be executed is determined
before the program runs, based on the method signature (name, parameters, and types).
How It Works: The compiler selects the appropriate method or operation based on the
number, types, and order of arguments at compile time.
Common Mechanisms:
Method Overloading: Defining multiple methods with the same name in the same class
but with different parameter lists (number or types of parameters).

Python doesn't support traditional method overloading like Java or C++ does.
Why This Doesn't Work in Python
Python doesn't support compile-time method overloading where you can have multiple methods with the same name but different parameter lists.
In Python:
Last Definition Wins: When you define multiple methods with the same name, the last one defined overwrites the previous ones.
Dynamic Nature: Python is dynamically typed, so it can't determine which method to call at compile time based on parameter types.
Run-time Polymorphism
Run-time polymorphism, also known as dynamic polymorphism, is resolved during the execution of the program.
The specific method to be called is determined at run time based on the actual type of the object.
How It Works: Achieved through method overriding, where a subclass provides a specific implementation of a
method defined in its parent class. The method called depends on the object’s type at run time, not the reference
type.
Common Mechanism:
Method Overriding: A subclass redefines a method from the parent class with the same name and signature,
providing a different implementation.
Often used with inheritance and a common parent class or or interface (e.g., an abstract base class).

Python fully supports run-time polymorphism through inheritance and method overriding.
Example-Method overloading
Example - Method Override
Example - Method Overriding abs..
abstract
In Python, abstraction is a key concept in object-oriented
programming (OOP) that focuses on hiding complex
implementation details and exposing only essential information to
the user.
It allows for the creation of simplified models of real-world
entities, making code more manageable and easier to understand.
Abstraction is achieved through abstract classes and methods.

An abstract class cannot be instantiated directly and serves as a


blueprint for other classes.
It can contain abstract methods, which are declared but not
defined within the abstract class.
Subclasses inheriting from the abstract class must provide
concrete implementations for these abstract methods.
This mechanism ensures that all subclasses adhere to a common
interface, promoting consistency and facilitating polymorphism
Abstract Class:
An abstract class is a class that cannot be instantiated directly
(i.e., you cannot create objects of an abstract class).
It serves as a template for other classes (subclasses) to inherit
from.
It may contain abstract methods (methods without
implementation) and concrete methods (methods with
implementation).
Abstract Method:
An abstract method is a method declared in an abstract class but
has no implementation in the abstract class itself.
Subclasses are required to provide an implementation for all
abstract methods, or they will also be considered abstract and
cannot be instantiated.
Subclasses inheriting from the abstract class must provide
concrete implementations for these abstract methods.
EXAMPLE
In this example, Shape is an abstract class with abstract methods area and
perimeter.
Circle and Square are concrete subclasses that inherit from Shape and
provide implementations for the abstract methods.
Attempting to instantiate Shape directly would result in an error, while
Circle and Square can be instantiated and their methods can be called.

Abstraction simplifies complex systems by focusing on essential aspects


and hiding unnecessary details. It enhances code readability,
maintainability, and flexibility, making it a fundamental principle in
software development.
YOU
ANK
TH

You might also like