Classes and Objects

Today I was kinda learning Classes and Objects and this blog is about what I kinda learned. Ok to start off, Classes are like blueprint, a plan. The blueprint consists of the general description of the future to be made object. The blueprint has certain attributes and certain behaviour of the future object to be made. If you take the blueprint of the car, The car consists of the certain attributes like 4 wheels, a front and back windows, a trunk, etcetra.. and some behaviour like accelerate forward, can reverse back, etc.. The Objects are the items that are made using the blueprint called classes. If you consider the Class Homo Sapiens a general blueprint would be that it has a face with eyes, nose, ears etc a body and limbs. But we know that not all homosapiens are the same, each and every homosapien has some unique features and characteristics that distinguishes it from others in the same species. Like that every object can have its own characteristics and features.
To Implement a class in python, a class generally contains 3 components
- Attributes
- Initializer
- Behaviour
Attributes are the characteristics that are represented using primitives, collections and objects. Initializer is used to create the object. It is kinda like constructor, which is when the object is made it automatically initializes some parts such as attributes that require setting up or performs some behaviour. Behaviour is implemented using methods. They are like the various operations that a object can do. If you consider the Class Homosapiens the Attributes could be things like hair colour, eye colour, height, etcetra. The Behaviour could be the ability to walk, jump, to speak etcetra. The Initializer could be to trigger the biological clock when you are born, to start the growth phase when born, etc. Objects and Classes are closely related to the real life scenarios. The Paradigms of modelling programs based on Classes and Objects is called as Object Oriented Programming. Let me create a Class and show you a working example of class. Let us Consider a class for a Gamecharacter.
class Gamecharacter: # Class definition
#Attributes/State
name = ""
jump_height = 10
health = 100
#Initializer
def __init__(self,name):
self.name = name #Object creation and automatic assignment of parameter to object's attribute
#Behaviour/method
def change_health(value):
health += value
if(health > 100):
health = 100
character_player1 = Gamecharacter(player1) #To create a instance of the class
character_player1.change_health(-10) #Player gets hurt in game
Here the keyword "self" refers to this class's item. We are assigning the parameter name to the class's own name attribute We can access the class's items such as attributes and behaviour using '.' operator



