Python - 21

Python - 21: Classes & Objects

Classes let you create your own kinds of objects and give each object its own data and behavior.

Your challenge: Create a class, store values with self, make two objects, and call a method on each one.

✦ Python Editor
▶ Output

Create a class

A class is a blueprint for creating objects: class Player:

Each object created from the class can store different values.

Use __init__()

__init__() runs when a new object is created.

Lines like self.name = name store information inside that specific object.

Create objects

This creates a new Player object: player1 = Player("Alex", 100)

Call methods

A method is a function that belongs to a class. Call it through an object: player1.show_stats()

Try it: Create a third player with a different name and health value.

Good Python habit: Class names usually begin with a capital letter, while methods and variables normally use lowercase names with underscores.

👀 Show Example Solution
class Player:

    def __init__(self, name, health):
        self.name = name
        self.health = health

    def show_stats(self):
        print("Player:")
        print(self.name)

        print("Health:")
        print(self.health)

player1 = Player("Alex", 100)
player2 = Player("Sam", 80)

player1.show_stats()
player2.show_stats()

Both objects come from the same Player class, but each one keeps its own name and health values.