# Exploring Key Object-Oriented Programming Concepts (Part 2)

Hello and welcome to today's blog! In our continuing exploration of the intriguing world of [Object-Oriented Programming](https://python.plainenglish.io/object-oriented-programming-oop-in-python-abstraction-encapsulation-ffc671cb2b00) ([OOP](https://www.learnvern.com/core-python-programming-tutorial-in-hindi/encapsulation-in-python)), we're about to uncover some essential notions at the heart of writing efficient and elegant [code](https://www.edureka.co/blog/object-oriented-programming-python/).

This blog explores [key Object-Oriented Programming](https://dotnettutorials.net/lesson/abstract-classes-in-python/) ([OOP](https://programming-21.mooc.fi/part-9/3-encapsulation)) concepts, focusing on [encapsulation](https://pythonprogramminglanguage.com/encapsulation/) and [abstraction](https://www.prepbytes.com/blog/python/abstraction-in-python/). These fundamental [OOP](https://www.learnvern.com/core-python-programming-tutorial/encapsulation-in-python) concepts are essential for becoming a proficient and creative programmer, regardless of experience or starting point.

So, buckle up and get ready to explore these foundational [OOP](https://www.educba.com/encapsulation-in-python/) concepts that will empower you to write [code](https://blog.finxter.com/data-abstraction-in-python-simply-explained/) that's secure, organized, and adaptable. Thank you for joining us today, and let's embark on this enlightening coding adventure together!

## [Encapsulation](https://www.youtube.com/watch?v=FDdfGFhY9Ms&ab_channel=edureka%21)

*"*[*Encapsulation*](https://www.tutorialspoint.com/what-is-encapsulation-in-python) *is the process of concealing an* [*object's*](https://www.msdotnet.co.in/2021/03/encapsulation-in-python-with-examples.html) *underlying information while giving a controlled interface to interact with it. It aids in* [*data*](https://www.sanfoundry.com/python-questions-answers-encapsulation/) *security by preventing unwanted access. "*

it refers to the combination of [data](https://www.cdslab.org/python/notes/object-oriented-programming/encapsulation/encapsulation.html) (attributes) and methods (functions or procedures) that operate on that [data](https://salesforcedrillers.com/learn-python/encapsulation/) into a single unit known as a [class](https://www.tutorialandexample.com/abstraction-in-python)

### [Key](https://www.composingprograms.com/pages/22-data-abstraction.html) Concepts in [Encapsulation](https://www.geeksforgeeks.org/encapsulation-in-python/)

* [**Data**](https://subscription.packtpub.com/book/programming/9781785884481/5/ch05lvl1sec39/encapsulation) **Hiding**
    
* **Public Interface**
    
* **Access Control**
    
* [**Data**](https://www.shiksha.com/online-courses/articles/abstraction-in-python/) **Integrity**
    
* **Flexibility and Maintenance**
    
* **Security**
    

### [**Data**](https://www.educative.io/answers/what-is-an-abstraction-in-python) **Hiding**

*"*[*Encapsulation*](https://pynative.com/python-encapsulation/) *conceals an* [*object's*](https://www.tutorjoes.in/python_programming_tutorial/abstraction_encap_in_python) *internal state or* [*data*](https://www.w3resource.com/python-interview/what-is-abstraction-in-oop-python.php) *from the outside world. This implies that the* [*data*](https://herovired.com/learning-hub/blogs/abstraction-in-python/) *contained within an* [*object*](https://www.w3schools.com/python/python_classes.asp) *is usually marked as private or protected, limiting direct access or alteration by external programs."*

**Example 1:** A bank account [class](https://www.nomidl.com/python/abstraction-in-python/) stores a private balance variable, preventing direct modification from outside the [class](https://learnetutorials.com/python/oops-encapsulation-data-abstraction). This is achieved by using language-specific conventions or access modifiers, allowing external [code](https://blog.finxter.com/data-abstraction-in-python-simply-explained/) to interact with the balance using the provided methods.

```python
class BankAccount:
    def __init__(self, account_number, initial_balance=0):
        self.__account_number = account_number  # Private attribute
        self.__balance = initial_balance        # Private attribute

    def deposit(self, amount):
        """Deposit funds into the account."""
        if amount > 0:
            self.__balance += amount

    def withdraw(self, amount):
        """Withdraw funds from the account."""
        if amount > 0 and amount <= self.__balance:
            self.__balance -= amount

    def get_balance(self):
        """Get the current balance of the account."""
        return self.__balance

    def get_account_number(self):
        """Get the account number (a read-only property)."""
        return self.__account_number

# Usage
account = BankAccount("12345", 1000)
print(f"Account Number: {account.get_account_number()}")
print(f"Initial Balance: {account.get_balance()}")

account.deposit(500)
print(f"Balance after deposit: {account.get_balance()}")

account.withdraw(200)
print(f"Balance after withdrawal: {account.get_balance()}")
```

### **Public Interface**

*"*[*Encapsulation*](https://www.youtube.com/watch?v=ypWwSv-zNKs&ab_channel=ProgrammingKnowledge) *offers a public interface, often consisting of methods or functions, in place of direct access to an* [*object's*](https://www.w3resource.com/python-interview/what-is-encapsulation-in-oop.php) *underlying* [*data*](https://www.learnvern.com/core-python-programming-tutorial/abstraction-in-python)*. These approaches provide for regulated* [*data*](https://medium.com/@samersallam92/8-abstraction-and-encapsulation-in-oop-18e1444609a4) *access and modification."*

**Example 2:** The TemperatureConverter [class](https://www.tutorjoes.in/python_programming_tutorial/abstraction_encap_in_python) maintains Celsius temperature [data](https://www.linkedin.com/pulse/abstraction-python-akhilesh-singh/), ensuring legitimate changes follow [class](https://stackoverflow.com/questions/10163197/abstraction-in-python) logic through public methods and logical constraints, connecting the outside world to inside [data](https://docs.python.org/3/library/abc.html).

```python
class TemperatureConverter:
    def __init__(self):
        self.__temperature_celsius = 0  # Private attribute to store temperature in Celsius

    def set_temperature_celsius(self, celsius):
        if celsius >= -273.15:  # Absolute zero in Celsius
            self.__temperature_celsius = celsius

    def set_temperature_fahrenheit(self, fahrenheit):
        celsius = (fahrenheit - 32) * 5/9
        self.set_temperature_celsius(celsius)  # Use the Celsius setter method

    def get_temperature_celsius(self):
        return self.__temperature_celsius

    def get_temperature_fahrenheit(self):
        fahrenheit = (self.__temperature_celsius * 9/5) + 32
        return fahrenheit

# Usage
converter = TemperatureConverter()

# Set the temperature in Celsius
converter.set_temperature_celsius(25)

# Get the temperature in Fahrenheit
fahrenheit = converter.get_temperature_fahrenheit()
print(f"Temperature in Fahrenheit: {fahrenheit}")

# Set the temperature in Fahrenheit
converter.set_temperature_fahrenheit(77)

# Get the temperature in Celsius
celsius = converter.get_temperature_celsius()
print(f"Temperature in Celsius: {celsius}")
```

### Access Control

*"By utilizing access modifiers such as "private," "protected," and "public,"* [*encapsulation*](https://www.youtube.com/watch?v=fjIUS1jlVkA&ab_channel=Jenny%27sLecturesCSIT) *determines who may access an* [*object's*](https://www.ibmmainframer.com/python-tutorial/encapsulation/) [*data*](https://www.faceprep.in/python/abstraction-in-python/) *and operations. This guarantees that* [*data*](https://www.youtube.com/watch?v=TenfEct8AxM&ab_channel=Jenny%27sLecturesCSIT) *is accessed and updated in a predictable and controlled way."*

* [Encapsulation](https://www.scaler.com/topics/python/encapsulation-in-python/) tags [data](https://www.section.io/engineering-education/abstraction-concepts/) members like balance variables as "private" to prevent direct external access, while methods that should be accessible to outside [code](https://www.w3schools.com/python/python_classes.asp) are labeled "public."
    

**Example 3:** [Encapsulation](https://www.javatpoint.com/encapsulation-in-python) controls and protects access to an [object's](https://github.com/topics/encapsulation?l=python) [data](https://www.gcreddy.com/2022/01/abstraction-in-python.html) through access modifiers and public methods, ensuring non-negative age and controlled interactions.

```python
class Person:
    def __init__(self, name, age):
        self.__name = name  # Private attribute
        self.__age = age    # Private attribute

    def get_age(self):
        return self.__age  # Public method to access age

    def set_age(self, new_age):
        if new_age >= 0:
            self.__age = new_age  # Public method to set age if it's non-negative

    def get_name(self):
        return self.__name  # Public method to access name

# Usage
person = Person("Alice", 30)
print(person.get_name())  # Accessing the name through a public method
print(person.get_age())   # Accessing the age through a public method

# Attempting to access the private attribute directly (will result in an error)
# print(person.__name)  # This line would raise an AttributeError
```

### [**Data**](https://github.com/topics/abstraction?l=python&o=asc&s=stars) **Integrity**

[Encapsulation](https://www.codingninjas.com/studio/library/what-is-encapsulation-in-python) contributes to [data](https://www.upgrad.com/blog/how-does-abstraction-work-in-python/) integrity by guaranteeing that [data](https://python.plainenglish.io/object-oriented-programming-oop-in-python-abstraction-encapsulation-ffc671cb2b00) is always accessed and updated via the defined procedures. This enables consistent validation, error-checking, and consistency checks.

**Example 4:** [Encapsulation](https://www.pythontutorial.net/python-oop/python-private-attributes/) enforces rules and checks on [data](https://www.freecodecamp.org/news/crash-course-object-oriented-programming-in-python/) by providing controlled access methods. For example, in a bank account, the withdrawal method checks if the withdrawal amount is valid and not negative, ensuring [data](https://www.boardinfinity.com/blog/understanding-encapsulation-in-python/) consistency and preventing erroneous or unintended modifications.

### Flexibility and Maintenance

[Encapsulation](https://wiingy.com/learn/python/encapsulation-in-python/) encourages [code](https://pypi.org/project/abstraction/) modularity. Changes to the internal implementation of a [class](https://www.ibmmainframer.com/python-tutorial/abstraction/) (for example, [data](https://pythonexamples.org/python-encapsulation/) structures or algorithms) are permissible as long as the public interface stays unchanged. This improves the [code](https://zetcode.com/lang/python/oop/)'s maintainability and flexibility.

**Example 5:** The BankAccount [class](https://codersdaily.in/courses/python-tutorial/abstraction) **introduces \_\_transactions**, a tuple-based [data](https://history-computer.com/encapsulation-in-python/) structure for transaction history, ensuring consistent behavior despite internal changes and allowing flexibility without extensive [code](https://earthly.dev/blog/abstract-base-classes-python/) changes.

### Security

[Encapsulation](https://www.educative.io/answers/what-is-encapsulation-in-python) can improve software system [security](https://subscription.packtpub.com/book/programming/9781785884481/5/ch05lvl1sec38/abstraction) by restricting [data](https://www.tutorialsfreak.com/python-tutorial/python-encapsulation) access. It stops unauthorized programs from changing sensitive [data](https://learnetutorials.com/python/oops-encapsulation-data-abstraction) directly.

**Example 6:** [Encapsulation](https://www.shiksha.com/online-courses/articles/encapsulation-in-python/) contributes to security by preventing unauthorized code from directly accessing or modifying sensitive [data](https://www.360digitalgyan.com/python/videos-tutorials/encapsulation-in-python). In the bank account example, if the balance variable were public, any code could change it arbitrarily, potentially causing financial errors or security breaches.

By restricting access to [data](https://www.netjstech.com/2019/04/encapsulation-in-python.html) and providing controlled methods, you can enforce security measures and prevent malicious or unintentional interference with the [object's](https://www.wolfram.com/language/fast-introduction-for-programmers/en/?compare=python&src=google&1701&gclid=CjwKCAjw69moBhBgEiwAUFCx2J815JdK28xT1v-YgWADPhmDakDzXHWZfOleLknyII3dMQAoxb8JxBoCJrEQAvD_BwE) state.

## [Abstraction](https://www.askpython.com/python/oops/abstraction-in-python)

*"*[*Abstraction*](https://www.javatpoint.com/abstraction-in-python) *is the process of simplifying complex reality by modeling* [*classes*](https://www.programiz.com/python-programming/object-oriented-programming) *based on essential properties and behaviors. It allows you to focus on what an* [*object*](https://edube.org/learn/python-advanced-1/encapsulation) *does, rather than how it does it."*

[Abstraction](https://www.geeksforgeeks.org/abstract-classes-in-python/) is a crucial concept in computer science and software engineering, simplifying complex systems by focusing on essential properties and ignoring irrelevant details, promoting reusability in software development.

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

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius * self.radius

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

# Creating shape objects
circle = Circle(5)
rectangle = Rectangle(4, 6)

# Calculating areas
print("Circle Area:", circle.area())       # Output: Circle Area: 78.53975
print("Rectangle Area:", rectangle.area()) # Output: Rectangle Area: 24
```

### [Key](https://www.freecodecamp.org/news/crash-course-object-oriented-programming-in-python/) Concepts in [Abstraction](https://www.tutorialspoint.com/python/python_abstraction.htm)

* **Identifying Essential Properties**
    
* **Creating a Generalized Representation**
    
* **Hiding Implementation Details**
    
* **Providing a Simplified Interface**
    

### **Identifying Essential Properties**

The process of [abstraction](https://www.geeksforgeeks.org/abstract-classes-in-python/) begins with identifying the fundamental traits or attributes of an item, system, or idea while disregarding non-essential or unnecessary information. At a higher level of comprehension, these [key](https://intellipaat.com/community/65099/abstraction-in-python) features are what define the [object](https://www.cosmiclearn.com/python/encapsulation.php) or notion.

In the context of a car, essential properties may include the ability to move, the ability to steer, the ability to stop, and the number of wheels. These are the core characteristics that define a car.

### **Creating a Generalized Representation**

Once the important traits are recognized, a generic representation that [encapsulates](https://www.tutlane.com/tutorial/python/encapsulation-in-python) these [key](https://dev.to/titusnjuguna/simplified-oop-abstraction-in-python-16ci) characteristics is produced. This representation is frequently in the form of a model, interface, or abstract [class](https://www.netjstech.com/2019/06/abstraction-in-python.html).

We can abstract an automobile by creating a generic representation known as a "**<mark>Car Interface.</mark>**" Methods defined by this interface include "**<mark>start</mark>**," "**<mark>stop</mark>**," "**<mark>accelerate</mark>**," "**<mark>turn</mark>**," and "**<mark>getNumberOfWheels</mark>**." These methods reflect a car's fundamental actions and attributes.

```python
interface Car:
    method start()
    method stop()
    method accelerate()
    method turn(direction)
    method getNumberOfWheels()
```

### **Hiding Implementation Details**

[Abstraction](https://www.mygreatlearning.com/blog/abstraction-in-python/#:~:text=Abstraction%20in%20python%20is%20defined,oriented%20programming%20(OOP)%20languages.) also entails concealing an [object's](https://pythonlobby.com/encapsulation-in-python-programming/) or system's implementation details. This signifies that the entity's interior workings and intricacies remain hidden from the outside world. Users simply need to know how to interact with the [abstraction](https://www.scaler.com/topics/python/data-abstraction-in-python/), not how it works within.

The mechanics of how each single automobile model is manufactured and works are hidden from users of the "**Car Interface.**" To utilize an automobile, users do not need to understand the complexities of the engine, gearbox, or brake system. They engage with the automobile using the techniques offered.

### Providing a Simplified Interface

[Abstraction](https://prepinsta.com/python/data-abstraction/) provides users with a simpler and well-defined interface or set of ways to interact with the thing. The activities that can be done on the [object](https://prepinsta.com/python/encapsulation/) and the [data](https://pythonpoint.net/what-is-encapsulation-in-python/) that may be accessed or altered are often included in this interface.

Users may design, drive, and manipulate automobiles using the techniques specified in the "**<mark>Car Interface</mark>**" without having to worry about the car's internal workings.

```python
myCar = createCar()  # Create a car object
myCar.start()        # Start the car
myCar.accelerate()   # Accelerate the car
myCar.turn("left")   # Turn the car left
myCar.stop()         # Stop the car
wheels = myCar.getNumberOfWheels()  # Get the number of wheels
```

[Abstraction](https://pythonlobby.com/abstraction-in-python-programming/) simplifies car concepts by focusing on essential properties and operations, ignoring the complexities of specific models. This promotes reusability as the same "**<mark>Car Interface</mark>**" can be used for various car implementations.

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent">This blog delves into the principles of <a target="_blank" rel="noopener noreferrer nofollow" href="https://pythonspot.com/encapsulation/" style="pointer-events: none">Object-Oriented Programming </a>(<a target="_blank" rel="noopener noreferrer nofollow" href="https://www.coursera.org/learn/object-oriented-python" style="pointer-events: none">OOP</a>) and <a target="_blank" rel="noopener noreferrer nofollow" href="https://kandi.openweaver.com/?landingpage=python_all_projects&amp;utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=promo_kandi_ie&amp;utm_content=kandi_ie_search&amp;utm_term=python_devs&amp;gclid=CjwKCAjw69moBhBgEiwAUFCx2OVTwYmgWhnLMnAkI3ZkLQW-OKigB2xcBVkGYuMiku_hbycM1vb47BoCAXoQAvD_BwE" style="pointer-events: none">encapsulation</a>, which are essential for creating secure, organized, and adaptable code. <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.programiz.com/python-programming/object-oriented-programming" style="pointer-events: none">Encapsulation</a> conceals an <a target="_blank" rel="noopener noreferrer nofollow" href="https://codersdaily.in/courses/python-tutorial/encapsulation" style="pointer-events: none">object's </a>internal <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.sanfoundry.com/python-questions-answers-encapsulation/" style="pointer-events: none">data</a>, provides a public interface, and ensures <a target="_blank" rel="noopener noreferrer nofollow" href="https://livebook.manning.com/concept/python/encapsulation" style="pointer-events: none">data</a> integrity. <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.educba.com/abstraction-in-python/" style="pointer-events: none">Abstraction</a> identifies essential properties, simplifies interfaces, and hides implementation details. Understanding these concepts allows programmers to write efficient, elegant <a target="_blank" rel="noopener noreferrer nofollow" href="https://innovationyourself.com/abstraction-in-python/" style="pointer-events: none">code </a>that can withstand software development's evolving landscape.</div></details>

We sincerely value your readership, and we don't want you to miss out on these insightful articles. So, please remain in touch and don't miss our forthcoming posts. Your continuing interest and support motivate us to present you with the greatest material available. Thank you for joining us on our quest to learn [Object-Oriented Programming](https://www.scaler.com/topics/oops-concepts-in-python/).

Thank you for reading our blog. Our top priority is your success and satisfaction. We are ready to assist with any questions or additional help.

Warm regards,

[**Kamilla Preeti Samuel,**](https://www.linkedin.com/in/preeti-samuel-kamilla-5a247962/)

**Content Editor**

[**ByteScrum Technologies Private Limited!**](https://www.bytescrum.com/) 🙏
