DEV Community

Cover image for Object-Oriented Programming; Python Classes and Objects.
Elizabeth Njoroge
Elizabeth Njoroge

Posted on

Object-Oriented Programming; Python Classes and Objects.

It's the weekend, you have nothing to do, you pick up the pad and turn on the screen.

A menu appears asking you to a new game, continue or logout. You hit a new game and the screen asks you to choose a character.

Now there are three dark figure with different stature, a warrior with a sword, a mage with a staff and a police man with a gun.

Those three figures are not the characters but they are the blueprint, you are the one who will create the characters by choice of the name or the health bar or even by the stats that each has.

Before pressing the done button that creates the character what is happening is the code is created is a Blueprint. It describes what every character in that game has.

Now after pressing that button what ran is now a character.

Object.
Now you are the object, the blueprint written was the class. While playing the game, the moment you start fighting or setting your name was the _ init _ and the self is how you refer yourself.

_init _
We need a way to give each character its own name, health and power. It defines the constructor.

     def __init__(self, name, health, power):
Enter fullscreen mode Exit fullscreen mode

Self
This is how a character refers to itself and the self.name= name stores the name argument as an attribute on the object.

   self.name = name
   self.health = health
   self.power = power
Enter fullscreen mode Exit fullscreen mode

Methods define the behaviour.

   def attack(self, target):
   def status(self):
Enter fullscreen mode Exit fullscreen mode

Difference between Class and Instance Attributes.
1.Class attributes belong to the class itself and are shared across every single character from that class. They are the global rules of the game.

   class Character:
        max_level = 99          
        game_version = "1.0" 
Enter fullscreen mode Exit fullscreen mode

2.Instance attributes belong to one object. They are now the individual names and stats.

    self.name = name
    self.health = health
    self.power = power
Enter fullscreen mode Exit fullscreen mode

_Str _ and _Repr _.
_Str _ is a string that that is intended for end users. It is what gets called when you use str() or print() on an object.

_Repr _ is a representation and is more for developers. It is what you see in the debug view.

Complete Class
One of a good example of a class is a bank account that combines the classes, attributes and methods.

Conclusion
Class Attributes acts like global rules for a game and affects all instances.
Instance Attributes hol object-specific like a characters name.
_repr _ is developers friendly.
_str _ is end-user friendly.

Top comments (1)

Collapse
 
suppdevbot profile image
DEV SUPPORTS •

You need to verify your account.

Enter fullscreen mode Exit fullscreen mode

tr.ee/dev-to