Introduction to Classes in Python Explained Simply (Basic OOP)

Published: (April 16, 2026 at 01:00 PM EDT)
2 min read
Source: Dev.to

Source: Dev.to

What is a class?

A class is a blueprint for creating objects. An object is an instance of a class.

Define a simple class

class Dog:
    pass

Create an object (instance)

my_dog = Dog()

Adding attributes

Attributes are variables that belong to an object. Use __init__ (the constructor) to set initial attributes.

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

Create objects with values

dog1 = Dog("Buddy", 3)
dog2 = Dog("Luna", 5)

print(dog1.name)  # Buddy
print(dog2.age)   # 5

self refers to the current object and is always the first parameter in methods.

Adding methods

Methods are functions that belong to a class.

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print("Woof!")

    def get_info(self):
        print(f"{self.name} is {self.age} years old.")

Call methods on objects

dog1 = Dog("Buddy", 3)

dog1.bark()       # Woof!
dog1.get_info()  # Buddy is 3 years old.

Simple examples

A basic Person class

class Person:
    def __init__(self, name, city):
        self.name = name
        self.city = city

    def introduce(self):
        print(f"Hi, I'm {self.name} from {self.city}.")

p = Person("Alex", "Berlin")
p.introduce()  # Hi, I'm Alex from Berlin.

A Rectangle class

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

rect = Rectangle(10, 5)
print(rect.area())  # 50

Important notes

  • Class names use CamelCase by convention.
  • __init__ runs automatically when creating an object.
  • All methods take self as the first parameter.
  • Attributes are accessed with dot notation (object.attribute).

Quick summary

  • Define classes with class.
  • Use __init__ to set initial attributes.
  • Add methods to define behavior.
  • Create objects with ClassName().
  • Access attributes and methods with dot notation.

Practice creating simple classes for real‑world objects. Classes help organize code and model data in Python programs.

0 views
Back to Blog

Related posts

Read more »