Skip to content
    Pythonia

    OBJECT-ORIENTED PROGRAMMING · 12 MIN

    Classes & Objects (OOP)

    A class is a blueprint; objects are things built from it, each with its own data.

    PYRA explains

    • __init__ sets up a new object's attributes; self refers to that object.
    • Methods are functions inside a class that use self.
    • Inheritance: class Mage(Player) reuses Player's code and can override parts of it.

    Real world: A car blueprint (class) and the actual cars in a parking lot (objects).

    Code

    class Player:
        def __init__(self, name, hp=100):
            self.name, self.hp = name, hp
        def hit(self, dmg):
            self.hp = max(0, self.hp - dmg)
            return self.hp
    class Mage(Player):
        def hit(self, dmg):
            return super().hit(dmg // 2)
    print(Player("Cubo").hit(30), Mage("Pyra").hit(30))
    Output ›
    70 85
    Try it in the online compiler →

    Checkpoint quiz

    What does self refer to?

    Mage(Player) means Mage…