DEV Community

Sameer Qaiser
Sameer Qaiser

Posted on

Python Classes: A Beginner's Guide to OOP

πŸ“Œ Quick Info

  • Topic: Classes and objects in Python
  • Target Audience: Beginners who know functions and dictionaries
  • Goal: Understand why classes exist and how to write one

1. Introduction

"For weeks, I stored everything in dictionaries. Then I had 10 players in a game, each with a name, score, and level β€” and I had to update all of them manually. That's when I learned about classes."


2. The Problem (Using Dictionaries for Everything)

player1 = {"name": "Ali", "score": 0, "level": 1}
player2 = {"name": "Sara", "score": 0, "level": 1}
player3 = {"name": "Ahmed", "score": 0, "level": 1}

def add_score(player, points):
    player["score"] += points

add_score(player1, 10)
print(player1["score"])  # 10
Enter fullscreen mode Exit fullscreen mode

Problem: Every player is a plain dictionary. No structure. Easy to typo. Hard to scale.


3. The Solution (With Classes)

lass Player:
    def _init_(self, name):
        self.name = name
        self.score = 0
        self.level = 1

    def add_score(self, points):
        self.score += points

player1 = Player("Ali")
player2 = Player("Sara")

player1.add_score(10)
print(player1.score)   
print(player2.score)   

Enter fullscreen mode Exit fullscreen mode

Every Player is now a Player object with its own data and its own methods.


4. How It Works (Line By Line)

Line 1: class Player: β€” Defines a new class called Player.

Line 2: def init(self, name): β€” This runs automatically when you create a new player. It's called the constructor.

Line 3-5: self.name = name β€” Stores data on the object. self refers to the specific instance.

Line 7: def add_score(self, points): β€” A method that belongs to the class.

Line 11: player1 = Player("Ali") β€” Creates an instance (an object) of the class.


5. What is self?

self is how Python knows which player you're talking about.

When you write player1.add_score(10), Python translates it to:

Player.add_score(player1, 10)
Enter fullscreen mode Exit fullscreen mode

So self = player1 in that call. It's the object the method was called on.

Rule: Every method inside a class takes self as its first parameter. No exceptions.


6. Real Example (My Practice)

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds.")
        else:
            self.balance -= amount

    def show_balance(self):
        print(f"{self.owner}: ${self.balance}")

account = BankAccount("Ali", 100)
account.deposit(50)
account.withdraw(30)
account.show_balance()
Enter fullscreen mode Exit fullscreen mode

Output:

Ali: $120
Enter fullscreen mode Exit fullscreen mode

7. Class vs Instance

class Dog:
    species = "Canis familiaris"  

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

dog1 = Dog("Rex")
dog2 = Dog("Max")

print(dog1.species)   
print(dog2.species)   
print(dog1.name)      
print(dog2.name)      
Enter fullscreen mode Exit fullscreen mode

Class attribute = shared by every instance.
Instance attribute = unique to each instance.


8. What I learned

Β· Classes bundle data and behavior together
Β· β€”initβ€” runs when you create a new instance
Β· Self is how methods know which instance they belong to
Β· Class attributes are shared, instance attributes are unique
Β· Classes make code easier to scale when you have many similar things


9. Conclusion

"Classes felt like overkill when I had one player. But when I had ten, they saved me hours. Now I reach for classes whenever I have multiple things with the same shape β€” because managing them manually is how bugs get born."

Top comments (0)