← Back to Blog
    TutorialMarch 01, 20248 min read

    Python OOP for Beginners: Classes and Objects Made Simple

    Learn object-oriented programming in Python from scratch. Understand classes, objects, attributes, methods, and inheritance with beginner friendly examples.

    Python OOP for Beginners

    Object-oriented programming, often shortened to OOP, is a way of organizing code around objects rather than loose functions. It helps you model real things in your programs and keep related data and behavior together. This guide starts from zero.

    What Is a Class

    A class is a blueprint. It describes what data an object holds and what actions it can perform. Think of a class as a cookie cutter and objects as the cookies it makes.

    class Dog:
        def __init__(self, name):
            self.name = name
    
    rex = Dog("Rex")
    print(rex.name)

    Understanding the Constructor

    The special method named init runs when you create an object. It sets up the starting data, called attributes, using the self keyword to refer to the new object.

    Adding Methods

    A method is a function that belongs to a class. It defines what an object can do. Methods always take self as their first parameter.

    class Dog:
        def __init__(self, name):
            self.name = name
        def bark(self):
            return self.name + " says woof"
    
    print(Dog("Rex").bark())

    Creating Many Objects

    One class can produce as many objects as you want, and each keeps its own data. This is what makes classes so reusable.

    class Dog:
        def __init__(self, name):
            self.name = name
    
    dogs = [Dog("Rex"), Dog("Fido")]
    for d in dogs:
        print(d.name)

    Inheritance

    Inheritance lets a new class build on an existing one. The child class gets everything from the parent and can add or change behavior.

    class Animal:
        def speak(self):
            return "some sound"
    
    class Cat(Animal):
        def speak(self):
            return "meow"
    
    print(Cat().speak())

    A Friendly String Form

    The str method controls how your object looks when printed. It makes objects readable and is one of the most useful methods to learn early.

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def __str__(self):
            return "(" + str(self.x) + ", " + str(self.y) + ")"
    
    print(Point(3, 4))

    When to Use OOP

    OOP shines when your program has many things that share behavior, such as users, products, or game characters. For tiny scripts, plain functions are fine. As programs grow, classes keep the structure clear.

    Keep Building

    Open the playground and create a class for a book with a title and an author. Adding your own attributes and methods is the best way to make these ideas stick.

    By PythonExecutor Team

    Related Articles