Abstraction

 Abstraction:

We will be able to do our work without bothering it is done. So that is abstraction.
Hide the implementation and only show necessary details to the user.
Example:

Flashlight:

  • When press on it, light glow
  • When press off, no light.
  • Work is done
  • But how it is done and how light glow up the internal mechanism is hidden to us.

Example with class:
Enemy.py
# file to define enemy class

class Enemy:
    typeOfEnemy: str
    healthPoints: int = 10
    attack_damage: int = 1
   
    def talk(self):
        print("I am an enemy")

Main.py
# file to use enemy class file

from Enemy import Enemy

enemy = Enemy()

enemy.talk() # This will call the talk method from the Enemy class

# print(enemy.typeOfEnemy) this part of code will fail
# as no value is assigned in class for this attribute.

enemy.typeOfEnemy = "Goblin"  # Assigning a value to the typeOfEnemy attribute
print(enemy.typeOfEnemy) # now it will work.
print(enemy.healthPoints)
print(enemy.attack_damage)

Why use Abstraction?

  • As it will make user to complete his task without understanding the functionality present behind to complete the task smoothly.
  • You can create simple and reusable code.
  • Allows for a better use of the DRY principle (Don't repeat yourself)
  • Enables Python objects to become more scalable.
Fully working code with functions to perform the work, it will show the use of abstraction.
Enemy.py
# file to define enemy class

class Enemy:
    typeOfEnemy: str
    healthPoints: int = 10
    attack_damage: int = 1
   
    def talk(self):
        print(f"I am a {self.typeOfEnemy}. Be prepared to fight!")

    def walk_forward(self):
        print(f"{self.typeOfEnemy} moves closer to you!")

    def attack(self):
        print(f"{self.typeOfEnemy} attacks you for {self.attack_damage} damage!")

Main.py
# file to use enemy class file

from Enemy import Enemy

enemy = Enemy()

# print(enemy.typeOfEnemy) this part of code will fail
# as no value is assigned in class for this attribute.

enemy.typeOfEnemy = "Goblin"  # Assigning a value to the typeOfEnemy attribute
enemy.talk() # This will call the talk method from the Enemy class
enemy.walk_forward() # This will call the walk_forward method from the Enemy class
enemy.attack() # This will call the attack method from the Enemy class
print(enemy.typeOfEnemy) # now it will work.
print(enemy.healthPoints)
print(enemy.attack_damage)


Comments

Popular posts from this blog

Post Request with Pydantic usage (input validator)

Code Scalability and Routing

CRUD Assignment