Introduction to OOP in Python

What is OOP?

Object-oriented programming (OOP) is one of the popular paradigms used in programming. In this concept, real-world entities are represented as objects. These objects have both attributes (properties) and behaviors (methods). This makes it easier to break down complex problems into manageable modules. This article will teach how to create classes and objects in Python.

Classes and Objects in Python

A class is a blueprint for creating objects, which are instances of the class. A class contains attributes (variables) and methods (functions) that define the behavior of the objects created from the class.

In Python, the syntax for creating a class involves using the class keyword followed by the name of the class. Here is an example of an empty class. The pass keyword indicates that it is an empty class.

class Person:

The class definition may contain the attributes and methods that define the behavior of the objects created from the class. This is done using the __init__() method:

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

The __init__() method is called when an object is created from the class. It initializes the attributes of the object with the values passed as arguments.

To instantiate objects in Python, we use the class name followed by parentheses. We have the option to pass arguments to the __init__() method, which will initialize the object's attributes.

person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

When we try to print an object, this is what gets printed on the console:

<main.Person object at 0x7f427bdb0fa0>

To control the output, we can use the __str__() method. It is a special method that is used to define how an object should be represented as a string. When an object is printed using the print() function or the __str__() function, Python calls the object's __str__() method to get its string representation.

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

    def __str__(self):
        return f"{} {self.age}"

person1 = Person("Alice", 25)

print(person1) #Alice 25

Self and class methods

The behavior of a class is defined using class methods. These methods take the self as the parameter. Other parameters can be passed as arguments alongside the self keyword. The self keyword is used within class definitions to refer to the instance of the class. When a method is called on an object created from a class, the object itself is passed as the first argument to the method, which is referred to as "self."

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

    def say_hello(self):
        print("Hello, my name is",")

p1 = Person("John")
p1.say_hello() #Hello, my name is John

In this post, we went through the fundamentals of OOP in Python, including creating classes and objects, accessing class properties and functions, and representing objects as strings using the __str__() method.