0% found this document useful (0 votes)
9 views30 pages

Python Object-Oriented Programming Guide

Python's object-oriented programming (OOP) paradigm utilizes classes and objects to model real-world entities, enhancing code organization and management. Key concepts include encapsulation, inheritance, polymorphism, and the use of the '__init__' method for initializing object attributes. This approach promotes modularity and code reuse, leading to improved software quality and productivity.

Uploaded by

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

Python Object-Oriented Programming Guide

Python's object-oriented programming (OOP) paradigm utilizes classes and objects to model real-world entities, enhancing code organization and management. Key concepts include encapsulation, inheritance, polymorphism, and the use of the '__init__' method for initializing object attributes. This approach promotes modularity and code reuse, leading to improved software quality and productivity.

Uploaded by

poojas22cs059
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What Is the Python Object-Oriented Programming Concept?

Python's object-oriented programming (OOP) paradigm is a programming style that builds software
using "objects" for design and organization. A class serves as a blueprint for constructing objects; an
object is an instance of that class. Developers can model real-world entities using OOP as objects
with methods (functions) that manipulate data and attributes (data). This method facilitates the
encapsulation, modularity, and reuse of code, which makes complex program management and
maintenance simpler. Python's OOP makes writing flexible, scalable code easier by utilizing the
concepts of inheritance, polymorphism, and encapsulation. This improves code quality and
productivity.

Example

class Animal:
def __init__(self, name, species):
[Link] = name
[Link] = species

def speak(self):
raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"

class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"

dog = Dog("Buddy", "Canine")


cat = Cat("Whiskers", "Feline")

print([Link]()) # Output: Buddy says Woof!


print([Link]()) # Output: Whiskers says Meow!

Python Class

Syntax
Python defines a class with the 'class' keyword, the class name, and a
colon. The special '__init__' function, the constructor used to initialize the
object's attributes, is one of the method definitions in the class body.

class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2

def method_name(self):
# Method body
pass

Example

This is an example that shows how to define a class and create an object
from it in its entirety:

# Defining a class named Car


class Car:
# Constructor to initialize attributes
def __init__(self, make, model, year):
[Link] = make
[Link] = model
[Link] = year

# Method to display car details


def display_info(self):
print(f"{[Link]} {[Link]} {[Link]}")

# Creating an object of the Car class


my_car = Car("Toyota", "Corolla", 2020)

# Accessing attributes
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
print(my_car.year) # Output: 2020
# Calling a method
my_car.display_info() # Output: 2020 Toyota Corolla

Explanation

1. Defining the Class

The ‘Car’ class is defined with an ‘__init__’ method to initialize the ‘make’,
‘model’, and ‘year’ attributes.

The ‘display_info’ method is defined to print the car's details.

2. Creating an Object

The object ‘my_car’ is created as an instance of the ‘Car’ class, initializing


its attributes with the values "Toyota", "Corolla", and 2020.

3. Accessing Attributes and Calling Methods

The object's attributes are accessed using dot notation (‘my_car.make,


my_car.model, my_car.year’).

The ‘display_info’ method is called on ‘my_car’ to print its details.

Python Objects

Overview

An instance of a class is what Python calls an object. Objects are the basic
building blocks of object-oriented programming (OOP). Objects can
represent real-world things by encapsulating behaviors (methods) and
data (attributes). Every object formed from a class can interact with other
objects via methods and have a distinct set of characteristics. Managing
and maintaining complicated programs is simpler when code is organized,
reusable, and modular, thanks to objects.
Creating an Object

In Python, an object cannot be created before a class has been


instantiated. Using the '__init__' method defined in the class, this process
initializes the object's attributes. The following methods are available
when creating an object in Python:

1. Standard Initialization

The most popular method for creating an object is this one. To use the
class, call it like any other function and give any necessary arguments to
the '__init__' method.

 Example
class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

def bark(self):
print("Woof!")

# Creating an object of the Dog class


my_dog = Dog("Buddy", 3)

# Accessing attributes and methods


print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 3
my_dog.bark() # Output: Woof!

2. Using Default Arguments

The __init__ method lets you set default values for parameters so you can
construct objects with fewer arguments.

 Example
class Dog:
def __init__(self, name="Unknown", age=0):
[Link] = name
[Link] = age

# Creating an object without passing arguments


stray_dog = Dog()
print(stray_dog.name) # Output: Unknown
print(stray_dog.age) # Output: 0

3. Using Class Methods

Objects can be created more precisely or tailored using class methods.


These methods can be utilized as substitute constructors and are defined
using the '@classmethod' decorator.

 Example
class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

@classmethod
def from_birth_year(cls, name, birth_year):
age = 2024 - birth_year
return cls(name, age)

# Creating an object using the class method


puppy = Dog.from_birth_year("Max", 2021)
print([Link]) # Output: Max
print([Link]) # Output: 3

4. Using Factory Methods

Functions that return new instances of a class are known as factory


methods. Usually, they are employed to contain the logic needed to
produce an object.

 Example
class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

def create_dog(name, age):


return Dog(name, age)

# Creating an object using a factory method


guard_dog = create_dog("Rex", 5)
print(guard_dog.name) # Output: Rex
print(guard_dog.age) # Output: 5

5. Using Copy Constructors

Moreover, you can make an item by replicating its properties from another
object. Modules like 'copy' can be used, or you can accomplish this by
yourself.

 Example
import copy

class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

original_dog = Dog("Buddy", 3)
copied_dog = [Link](original_dog)

print(copied_dog.name) # Output: Buddy


print(copied_dog.age) # Output: 3

The_init_method

The constructor, also known as the '__init__' method in Python, is a unique


function that is invoked automatically upon creating a new instance of a
class. Its main objective is initializing the object's attributes with the
values supplied upon instantiation. The first parameter for this function is
'self', which corresponds to the instance being formed. Any other
parameters needed to populate the object's attributes are then sent in.
You can establish an object's initial state with the '__init__' method,
ensuring it is correctly initialized and prepared for use.

Example
class Person:
def __init__(self, name, age):
[Link] = name # Initialize instance attribute 'name'
[Link] = age # Initialize instance attribute 'age'

def display_info(self):
print(f"Name: {[Link]}, Age: {[Link]}")

# Creating an object of the Person class


person1 = Person("Alice", 30)

# Accessing attributes
print([Link]) # Output: Alice
print([Link]) # Output: 30

# Calling a method
person1.display_info() # Output: Name: Alice, Age: 30

Python Inheritance

Object-oriented programming (OOP) is based on the fundamental idea of


inheritance, which lets a class inherit properties and functions from
another class. This encourages the reuse of code and aids in developing a
hierarchical structure among classes. In Python, a new class called a
derived class can be created by inheriting from an existing class called a
base class.

Types of Inheritance
1. Single Inheritance

A derived class inherits from a single base class.

 Example
class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"

dog = Dog("Buddy")
print([Link]()) # Output: Buddy says Woof!

2. Multiple Inheritance

A derived class inherits from more than one base class.

 Example
class Animal:
def __init__(self, name):
[Link] = name

class Canine:
def bark(self):
return "Woof!"

class Dog(Animal, Canine):


def speak(self):
return f"{[Link]} says {[Link]()}"

dog = Dog("Buddy")
print([Link]()) # Output: Buddy says Woof!

3. Multilevel Inheritance
A derived class inherits from another derived class.

 Example
class Animal:
def __init__(self, name):
[Link] = name

class Mammal(Animal):
def __init__(self, name, has_fur):
super().__init__(name)
self.has_fur = has_fur

class Dog(Mammal):
def speak(self):
return f"{[Link]} says Woof!"

dog = Dog("Buddy", True)


print([Link]()) # Output: Buddy says Woof!

4. Hierarchical Inheritance

Multiple derived classes inherit from a single base class.

 Example
class Animal:
def __init__(self, name):
[Link] = name

class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"

class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")
print([Link]()) # Output: Buddy says Woof!
print([Link]()) # Output: Whiskers says Meow!

5. Hybrid Inheritance

A combination of two or more types of inheritance. It usually involves a


mix of hierarchical, multilevel, and multiple inheritance.

 Example
class Animal:
def __init__(self, name):
[Link] = name

class Canine(Animal):
def bark(self):
return "Woof!"

class Feline(Animal):
def meow(self):
return "Meow!"

class Dog(Canine):
def speak(self):
return f"{[Link]} says {[Link]()}"

class Cat(Feline):
def speak(self):
return f"{[Link]} says {[Link]()}"

dog = Dog("Buddy")
cat = Cat("Whiskers")
print([Link]()) # Output: Buddy says Woof!
print([Link]()) # Output: Whiskers says Meow!

Python Polymorphism

One of the fundamental ideas of object-oriented programming


is polymorphism, which enables objects of many classes to be viewed as
members of a single superclass. It allows several underlying forms (data
types) to be represented via a single interface. Python allows for
implementing polymorphism through method overloading and overriding,
enabling distinct classes to provide methods with the same name but
differing behavior according to the object's class. Building generic,
reusable code becomes more straightforward due to the promotion of
flexibility and integration.

 Example

This is an illustration of polymorphism in Python:

class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

def make_animal_speak(animal):
print([Link]())

dog = Dog()
cat = Cat()

make_animal_speak(dog) # Output: Woof!


make_animal_speak(cat) # Output: Meow!

Python Encapsulation
One of the core ideas of object-oriented programming is encapsulation,
which is the grouping of methods (functions) and data (attributes) into a
class unit. It also prevents unauthorized access to parts of the object's
components, which helps guard against data misuse and unintentional
interference. Usually, this is accomplished by utilizing a leading
underscore or double underscore to make certain attributes or methods
private. Encapsulation, which allows controlled access through public
methods, encourages modularity and aids in maintaining the integrity of
the object's data.

 Example

This is an illustration of Python encapsulation:

class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
self.__balance = balance # Private attribute

def deposit(self, amount):


if amount > 0:
self.__balance += amount
print(f"Deposited {amount}. New balance: {self.__balance}")
else:
print("Deposit amount must be positive.")

def withdraw(self, amount):


if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew {amount}. New balance: {self.__balance}")
else:
print("Invalid withdrawal amount.")

def get_balance(self):
return self.__balance

# Creating an object of the BankAccount class


account = BankAccount("Alice", 1000)
# Accessing public method
[Link](500) # Output: Deposited 500. New balance: 1500
[Link](200) # Output: Withdrew 200. New balance: 1300

# Trying to access private attribute directly (not recommended)


# print(account.__balance) # This will raise an AttributeError

# Accessing private attribute through public method


print(account.get_balance()) # Output: 1300

In this example, the 'BankAccount' class has the methods (deposit,


withdraw, and get_balance) that manipulate the data and the data itself
(owner and balance). One cannot directly access the private '__balance'
attribute outside the class. As an alternative, the public methods
"deposit," "withdraw," and "get_balance" can be used to access and
modify it. This preserves data integrity and encourages encapsulation
by guaranteeing that the balance can only be altered through regulated
procedures.

Object-Oriented Programming in
Python
Lesson 20 of 51By Avijeet Biswal
Last updated on Jun 21, 202448791

PreviousNext

Table of Contents
What Is the Python Object-Oriented Programming Concept?
Python Class
Python Objects
The_init_method
Python Inheritance
View More

Comprehending objects and classes is essential for becoming proficient in


Python object-oriented programming. This paradigm offers a structured
method for managing and organizing code by enabling developers to add,
edit, and remove items. You can construct object blueprints by using
classes, which encapsulate behaviors and data corresponding to real-
world entities. With the help of this article, you will learn how to create,
edit, and remove Python objects and classes, giving you the tools you
need to perform object oriented programming in Python for more reliable,
scalable, and maintainable programs.

Master Web Scraping, Django & More!


Python Certification CourseENROLL NOW

What Is the Python Object-Oriented Programming


Concept?

Python's object-oriented programming (OOP) paradigm is a programming


style that builds software using "objects" for design and organization. A
class serves as a blueprint for constructing objects; an object is an
instance of that class. Developers can model real-world entities using OOP
as objects with methods (functions) that manipulate data and attributes
(data). This method facilitates the encapsulation, modularity, and reuse of
code, which makes complex program management and maintenance
simpler. Python's OOP makes writing flexible, scalable code easier by
utilizing the concepts of inheritance, polymorphism, and encapsulation.
This improves code quality and productivity.
Example

class Animal:
def __init__(self, name, species):
[Link] = name
[Link] = species

def speak(self):
raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"

class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"

dog = Dog("Buddy", "Canine")


cat = Cat("Whiskers", "Feline")

print([Link]()) # Output: Buddy says Woof!


print([Link]()) # Output: Whiskers says Meow!

Dive Deep into Core Python Concepts


Python Certification CourseENROLL NOW

Python Class

Syntax

Python defines a class with the 'class' keyword, the class name, and a
colon. The special '__init__' function, the constructor used to initialize the
object's attributes, is one of the method definitions in the class body.

class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2

def method_name(self):
# Method body
pass

Example

This is an example that shows how to define a class and create an object
from it in its entirety:

# Defining a class named Car


class Car:
# Constructor to initialize attributes
def __init__(self, make, model, year):
[Link] = make
[Link] = model
[Link] = year

# Method to display car details


def display_info(self):
print(f"{[Link]} {[Link]} {[Link]}")

# Creating an object of the Car class


my_car = Car("Toyota", "Corolla", 2020)

# Accessing attributes
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
print(my_car.year) # Output: 2020

# Calling a method
my_car.display_info() # Output: 2020 Toyota Corolla

Explanation
1. Defining the Class

The ‘Car’ class is defined with an ‘__init__’ method to initialize the ‘make’,
‘model’, and ‘year’ attributes.

The ‘display_info’ method is defined to print the car's details.

2. Creating an Object

The object ‘my_car’ is created as an instance of the ‘Car’ class, initializing


its attributes with the values "Toyota", "Corolla", and 2020.

Seize the Opportunity: Become a Python


Developer!
Python Certification CourseENROLL NOW

3. Accessing Attributes and Calling Methods

The object's attributes are accessed using dot notation (‘my_car.make,


my_car.model, my_car.year’).

The ‘display_info’ method is called on ‘my_car’ to print its details.

Python Objects

Overview

An instance of a class is what Python calls an object. Objects are the basic
building blocks of object-oriented programming (OOP). Objects can
represent real-world things by encapsulating behaviors (methods) and
data (attributes). Every object formed from a class can interact with other
objects via methods and have a distinct set of characteristics. Managing
and maintaining complicated programs is simpler when code is organized,
reusable, and modular, thanks to objects.
Creating an Object

In Python, an object cannot be created before a class has been


instantiated. Using the '__init__' method defined in the class, this process
initializes the object's attributes. The following methods are available
when creating an object in Python:

1. Standard Initialization

The most popular method for creating an object is this one. To use the
class, call it like any other function and give any necessary arguments to
the '__init__' method.

 Example
class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

def bark(self):
print("Woof!")

# Creating an object of the Dog class


my_dog = Dog("Buddy", 3)

# Accessing attributes and methods


print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 3
my_dog.bark() # Output: Woof!

Skyrocket Your Career: Earn Top Salaries!


Python Certification CourseENROLL NOW

2. Using Default Arguments

The __init__ method lets you set default values for parameters so you can
construct objects with fewer arguments.
 Example
class Dog:
def __init__(self, name="Unknown", age=0):
[Link] = name
[Link] = age

# Creating an object without passing arguments


stray_dog = Dog()
print(stray_dog.name) # Output: Unknown
print(stray_dog.age) # Output: 0

3. Using Class Methods

Objects can be created more precisely or tailored using class methods.


These methods can be utilized as substitute constructors and are defined
using the '@classmethod' decorator.

 Example
class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

@classmethod
def from_birth_year(cls, name, birth_year):
age = 2024 - birth_year
return cls(name, age)

# Creating an object using the class method


puppy = Dog.from_birth_year("Max", 2021)
print([Link]) # Output: Max
print([Link]) # Output: 3

4. Using Factory Methods

Functions that return new instances of a class are known as factory


methods. Usually, they are employed to contain the logic needed to
produce an object.
 Example
class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

def create_dog(name, age):


return Dog(name, age)

# Creating an object using a factory method


guard_dog = create_dog("Rex", 5)
print(guard_dog.name) # Output: Rex
print(guard_dog.age) # Output: 5

Get Certified in Machine Learning


Machine Learning using PythonEXPLORE PROGRAM

5. Using Copy Constructors

Moreover, you can make an item by replicating its properties from another
object. Modules like 'copy' can be used, or you can accomplish this by
yourself.

 Example
import copy

class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

original_dog = Dog("Buddy", 3)
copied_dog = [Link](original_dog)

print(copied_dog.name) # Output: Buddy


print(copied_dog.age) # Output: 3
The_init_method

The constructor, also known as the '__init__' method in Python, is a unique


function that is invoked automatically upon creating a new instance of a
class. Its main objective is initializing the object's attributes with the
values supplied upon instantiation. The first parameter for this function is
'self', which corresponds to the instance being formed. Any other
parameters needed to populate the object's attributes are then sent in.
You can establish an object's initial state with the '__init__' method,
ensuring it is correctly initialized and prepared for use.

Fast-track Your Career in AI & Machine


Learning!
Machine Learning using PythonEXPLORE PROGRAM

Example
class Person:
def __init__(self, name, age):
[Link] = name # Initialize instance attribute 'name'
[Link] = age # Initialize instance attribute 'age'

def display_info(self):
print(f"Name: {[Link]}, Age: {[Link]}")

# Creating an object of the Person class


person1 = Person("Alice", 30)

# Accessing attributes
print([Link]) # Output: Alice
print([Link]) # Output: 30

# Calling a method
person1.display_info() # Output: Name: Alice, Age: 30
Python Inheritance

Object-oriented programming (OOP) is based on the fundamental idea of


inheritance, which lets a class inherit properties and functions from
another class. This encourages the reuse of code and aids in developing a
hierarchical structure among classes. In Python, a new class called a
derived class can be created by inheriting from an existing class called a
base class.

Types of Inheritance

1. Single Inheritance

A derived class inherits from a single base class.

 Example
class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"

dog = Dog("Buddy")
print([Link]()) # Output: Buddy says Woof!

Unleash Your Career as a Full Stack


Developer!
Full Stack Developer - MERN StackEXPLORE COURSE

2. Multiple Inheritance
A derived class inherits from more than one base class.

 Example
class Animal:
def __init__(self, name):
[Link] = name

class Canine:
def bark(self):
return "Woof!"

class Dog(Animal, Canine):


def speak(self):
return f"{[Link]} says {[Link]()}"

dog = Dog("Buddy")
print([Link]()) # Output: Buddy says Woof!

3. Multilevel Inheritance

A derived class inherits from another derived class.

 Example
class Animal:
def __init__(self, name):
[Link] = name

class Mammal(Animal):
def __init__(self, name, has_fur):
super().__init__(name)
self.has_fur = has_fur

class Dog(Mammal):
def speak(self):
return f"{[Link]} says Woof!"

dog = Dog("Buddy", True)


print([Link]()) # Output: Buddy says Woof!

4. Hierarchical Inheritance
Multiple derived classes inherit from a single base class.

 Example
class Animal:
def __init__(self, name):
[Link] = name

class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"

class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")
print([Link]()) # Output: Buddy says Woof!
print([Link]()) # Output: Whiskers says Meow!

Advance Your MERN Stack Career in 6


Months!
Full Stack Developer - MERN StackEXPLORE COURSE

5. Hybrid Inheritance

A combination of two or more types of inheritance. It usually involves a


mix of hierarchical, multilevel, and multiple inheritance.

 Example
class Animal:
def __init__(self, name):
[Link] = name

class Canine(Animal):
def bark(self):
return "Woof!"
class Feline(Animal):
def meow(self):
return "Meow!"

class Dog(Canine):
def speak(self):
return f"{[Link]} says {[Link]()}"

class Cat(Feline):
def speak(self):
return f"{[Link]} says {[Link]()}"

dog = Dog("Buddy")
cat = Cat("Whiskers")
print([Link]()) # Output: Buddy says Woof!
print([Link]()) # Output: Whiskers says Meow!

Become a Full Stack Developer in Just 6


Months!
Full Stack Developer - MERN StackEXPLORE COURSE

Python Polymorphism

One of the fundamental ideas of object-oriented programming


is polymorphism, which enables objects of many classes to be viewed as
members of a single superclass. It allows several underlying forms (data
types) to be represented via a single interface. Python allows for
implementing polymorphism through method overloading and overriding,
enabling distinct classes to provide methods with the same name but
differing behavior according to the object's class. Building generic,
reusable code becomes more straightforward due to the promotion of
flexibility and integration.

 Example
This is an illustration of polymorphism in Python:

class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

def make_animal_speak(animal):
print([Link]())

dog = Dog()
cat = Cat()

make_animal_speak(dog) # Output: Woof!


make_animal_speak(cat) # Output: Meow!

Master Web Scraping, Django & More!


Python Certification CourseENROLL NOW

Python Encapsulation

One of the core ideas of object-oriented programming is encapsulation,


which is the grouping of methods (functions) and data (attributes) into a
class unit. It also prevents unauthorized access to parts of the object's
components, which helps guard against data misuse and unintentional
interference. Usually, this is accomplished by utilizing a leading
underscore or double underscore to make certain attributes or methods
private. Encapsulation, which allows controlled access through public
methods, encourages modularity and aids in maintaining the integrity of
the object's data.

 Example

This is an illustration of Python encapsulation:

class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
self.__balance = balance # Private attribute

def deposit(self, amount):


if amount > 0:
self.__balance += amount
print(f"Deposited {amount}. New balance: {self.__balance}")
else:
print("Deposit amount must be positive.")

def withdraw(self, amount):


if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew {amount}. New balance: {self.__balance}")
else:
print("Invalid withdrawal amount.")

def get_balance(self):
return self.__balance

# Creating an object of the BankAccount class


account = BankAccount("Alice", 1000)

# Accessing public method


[Link](500) # Output: Deposited 500. New balance: 1500
[Link](200) # Output: Withdrew 200. New balance: 1300

# Trying to access private attribute directly (not recommended)


# print(account.__balance) # This will raise an AttributeError
# Accessing private attribute through public method
print(account.get_balance()) # Output: 1300

In this example, the 'BankAccount' class has the methods (deposit,


withdraw, and get_balance) that manipulate the data and the data itself
(owner and balance). One cannot directly access the private '__balance'
attribute outside the class. As an alternative, the public methods
"deposit," "withdraw," and "get_balance" can be used to access and
modify it. This preserves data integrity and encourages encapsulation
by guaranteeing that the balance can only be altered through regulated
procedures.

Dive Deep into Core Python Concepts


Python Certification CourseENROLL NOW

Data Abstraction

The goal of object-oriented programming's data abstraction principle is to


conceal a system's intricate implementation details from the user and
only reveal to them the elements that are essential and pertinent. Data
abstraction contributes to efficiency gains and complexity reduction by
offering a straightforward and uncomplicated interface. It enables
programmers to work with a simplified system representation and
manage complex operations. Abstract classes and interfaces in Python
can be used to create data abstraction. They specify methods derived
classes must be implemented to guarantee a standardized and
streamlined interaction with the underlying data.

 Example

This is an illustration of how to use abstract base classes to achieve data


abstraction in Python:

from abc import ABC, abstract method


class Shape(ABC):
@abstractmethod
def area(self):
pass

@abstractmethod
def perimeter(self):
pass

class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height

def area(self):
return [Link] * [Link]

def perimeter(self):
return 2 * ([Link] + [Link])

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14 * [Link] ** 2

def perimeter(self):
return 2 * 3.14 * [Link]

# Creating objects of Rectangle and Circle


rect = Rectangle(10, 20)
circ = Circle(15)

# Accessing area and perimeter methods


print(f"Rectangle Area: {[Link]()}") # Output: Rectangle Area: 200
print(f"Rectangle Perimeter: {[Link]()}") # Output: Rectangle Perimeter: 60
print(f"Circle Area: {[Link]()}") # Output: Circle Area: 706.5
print(f"Circle Perimeter: {[Link]()}") # Output: Circle Perimeter: 94.2

The abstract base class "Shape" in this example has abstract methods
"area" and "perimeter." Any concrete subclass must implement these
methods. Concrete classes called "Rectangle" and "Circle" implement the
abstract methods of "Shape" and are descended from it. By hiding the
intricate complexities of calculating area and perimeter, this abstraction
offers a straightforward and standardized user interface for working with
various shapes. Data abstraction simplifies code maintainability and
interaction by enabling the user to work with different shapes
without comprehending the underlying mathematics.

You might also like