Constructors
Constructors
Used to create and initialize an object of a class with or without starting/initial values.
enemy = Enemy() # calling a constructor of the class Enemy() -> This keyword.
Different types of Constructors:
- Default/ Empty Constructors - enemy = Enemy()
- No Argument Constructors - enemy = Enemy()
- Parameter Constructors - enemy = Enemy(typeOfEnemy="Dragon")
Enemy.py
# file to define enemy class
class Enemy:
# If you have constructors with parameters then you don't need to
# define attributes exclusively in class.
# typeOfEnemy: str
# healthPoints: int = 10
# attack_damage: int = 1
# This constructor will be created by python automatically if we do not define it.
# But we are defining it here to show that we can create a constructor
# with no parameters.
# Can force it to do nothing.
# It will get activated when we create an instance of the class.
# like -> enemy = Enemy()
"""
def __init__(self): # self refers to the current instance of the class
# Default or empty constructor
# which is defined by us but will not perform any task.
pass # it means just bypass the constructor and do nothing.
# No Argument Constructor
def __init__(self):
print('New enemy created! with no inital values.')
"""
# Parameterized Constructor
def __init__(self, typeOfEnemy: str,
healthPoints: int = 10, attack_damage: int = 1):
self.typeOfEnemy = typeOfEnemy
self.healthPoints = healthPoints
self.attack_damage = attack_damage
print(f'New enemy created! Type: {self.typeOfEnemy},
Health: {self.healthPoints}, Attack Damage: {self.attack_damage}')
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() # calling a constructor of the class Enemy() -> This keyword.
# 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)
"""
enemy2 = Enemy(typeOfEnemy="Orc", healthPoints=20, attack_damage=5) # Creating another
instance of the Enemy class with parameters
enemy3 = Enemy(typeOfEnemy="Dragon") # Creating another instance of the Enemy class
with parameters
Comments
Post a Comment