OOPs in python

 OOPS

It is a programming paradigm based on the concepts of objects, which can contain data and code.

OOPs benefits:

  • Scalability
  • Efficiency
  • Reusability

Objects:

  • Any thing which has behavior and consume memory are objects.
  • like - trees, animals, windows, house, anything which can act and can be touched and have some usage or usability.
  • Anything which can be used to code is object.

How to define an object?

  • Behavior - activity which an object can perform like dog can bark, eat, drink, sleep etc...
  • State - notations which can help to define object look. like dog - 4legs, 2 ears, age -5, color - yellow, breed or category - Goldendoodle.

Primitive datatypes:

sample:
leg: int = 4
ears: int = 2
type: str = 'Goldendoodle'
age: int = 5
color: str = 'Yellow'

Above one is collection of variables but they are not object.

Creating object in python:

file named: dog.py
Content:
# Defining dog class sample for practice

class Dog:
    leg: int = 4
    ears: int = 2
    type: str = 'Goldendoodle'
    age: int = 5
    color: str = 'Yellow'

dogclassuse.py
Content:
from dogclass import *

dog = Dog()
print(dog.leg)
print(dog.ears)
print(dog.type)
print(dog.age)
print(dog.color)

4 Pillars of OOPS concept:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

Sample program to learn OOPs?

  • Small game where we can create enemies that fight each other like an arena where gladiator fight will take place.

Acceptance criteria:

  • Enemies that can fight one another
  • Different types of enemies
    • Zombie
    • Ogre
  • Each enemy has different powers, health points and attack damage

Objective:

  • Implement OOPs concept.
  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

Enemy Object:

  • Name/Type of enemy
  • Health points
  • Attack damage
Enemy.py
class Enemy:
    typeOfEnemy: str
    healthPoints: int = 10
    attack_damage: int = 1

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
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