DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Introduction to Classes in Python Explained Simply (Basic OOP)

Classes let you create your own data types by combining data and functions. This is the start of object-oriented programming (OOP) in Python.

What is a class?

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

Define a simple class with the class keyword:

class Dog:
    pass
Enter fullscreen mode Exit fullscreen mode

Create an object (instance):

my_dog = Dog()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Create objects with values:

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

print(dog1.name)  # Buddy
print(dog2.age)   # 5
Enter fullscreen mode Exit fullscreen mode

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.")
Enter fullscreen mode Exit fullscreen mode

Call methods on objects:

dog1 = Dog("Buddy", 3)

dog1.bark()       # Woof!
dog1.get_info()   # Buddy is 3 years old.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)