OOP

kimchigood·2025년 4월 20일
0

FastAPI

목록 보기
1/1
post-thumbnail

This post of series is based on Udemy FastAPI - The Complete Course 2025 by Eric Roby

Object Oriented Programming?

Object Oriented Programming(OOP) is a programming pradadigm based on the concepts of objects, which can contain data and code.

  • Benefits
    • Scalability
    • Efficiency
    • Reusability

1. Abstraction?

Abstraction means to hide the implementation and only show necessary details to the user.

Why use Abstraction?

  • This allows users to not have to understandd what the functionality is behind scenes.
  • 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.

example code

# Enemy.py

class Enemy:

    type_of_enemy: str
    health_points: int = 10
    attack_damage: int = 1

    def talk(self):
        print(f"I am a {self.type_of_enemy}. Be prepared to fight!")
# main.py

from Enemy import *

zombie = Enemy()

zombie.type_of_enemy = 'Zombie'
print(f'{zombie.type_of_enemy} has {zombie.health_points} health points and can do attack of {zombie.attack_damage}')

zombie.talk()

2. Constructors?

Constructors are used to create and initialize an object of a class with or without starting values.

from Enemy import *
enemy = Enemy() # calling a constructor

Types of constructors

self resfers to the current class or object.

Default / Empty Constructors

class Enemy:

    type_of_enemy: str
    health_points: int = 10
    attack_damage: int = 1

    def __init__(self):
        pass

==> Automatically created if no constructor is found.

No Argument Constructors

class Enemy:

    type_of_enemy: str
    health_points: int = 10
    attack_damage: int = 1

    def __init__(self):
        print("I'm a enemy")

Parameter Constructors

class Enemy:

    type_of_enemy: str
    health_points: int = 10
    attack_damage: int = 1

    def __init__(self, type_of_enemy, health_points = 10, attack_damage = 1):
        self.type_of_enemy = type_of_enemy
        self.health_points = health_points
        self.attack_damage = attack_damage
        
---
zombie = Enemy('Zombie', 10, 1)
profile
Shout out to Kubernetes⎈

0개의 댓글