How to create a simple class

Define a class

A class is a blueprint for objects. __init__ initializes each new instance, and self refers to that instance.

class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

ada = Student("Ada", 95)
print(ada.name, ada.score)

Add behavior with methods

Instance methods receive self first and can read or update instance attributes.

class Counter:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1

counter = Counter()
counter.increment()
print(counter.value)

Create a readable representation

A __str__ method controls user-friendly text produced by str() and print().

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f"{self.title} by {self.author}"

print(Book("Python Basics", "A. Learner"))

Know when to use a class

  • Use a class when related data and behavior form a meaningful reusable concept.
  • Use a function when no lasting object state is needed.
  • Use a dictionary or tuple for simple data records that need little behavior.
  • Prefer composition and small classes before reaching for complex inheritance.