PYTHON LESSON 21 OF 32

Classes: build your own objects

A class describes a kind of object. __init__ sets up each new instance. self refers to that instance. Methods are functions attached to the class. Each instance can keep its own state.

हिन्दी में समझें

क्लास किसी वस्तु की रूपरेखा है। __init__ नया इंस्टेंस तैयार करता है। self उसी इंस्टेंस को बताता है। मेथड क्लास से जुड़ा फ़ंक्शन है।

अभ्यास: Dev नाम का Player बनाएँ और उसका अभिवादन प्रिंट करें।

Hinglish mein samjhein

Class object ka blueprint hai. __init__ naya instance set karta hai. self usi instance ko refer karta hai. Methods class ke functions hote hain.

Practice: Dev naam ka Player banao aur greeting print karo.

A small Python example

class Player:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hi, {self.name}"

print(Player("Asha").greet())

The browser playground runs real Python with Pyodide. Use sample variables instead of interactive input(). Browser package support differs from desktop Python.

Try this example in the Python playground →

Practise this idea

Create a Player named Dev and print their greeting.

Check answer & explanation
class Player:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hi, {self.name}"

print(Player("Dev").greet())

__init__ stores each player name on its instance. greet() reads that instance name, so a Dev player says Hi, Dev.

Stuck in the course? Choose Check answer for either the challenge or quiz. Read the explanation and continue to the next lesson at your own pace.

Check your understanding

What does self refer to?

  1. The current instance
  2. Every class
  3. A text string
Check the quiz answer

The current instance

self is the conventional name for the current object instance.

References & corrections

Use the official Python documentation for full language rules. Read how these lessons are made and checked. Found a mistake? Report it to Excel Keys with this lesson URL and a reproducible example.

FROM LEARNING TO BUSINESS RESULTS

Need a dashboard for your team?

Excel Keys designs custom Excel and HTML dashboards around your own KPIs and Excel files. They run offline in the browser, so your data stays on your computer.