A Beginner’s Guide to Object-Oriented Programming (OOP) in Python

Louie
4 min readApr 17, 2024

--

Welcome back to our journey into Python programming! In this post, I’ll be diving into the world of Object-Oriented Programming (OOP). OOP is a powerful paradigm that allows you to organize and structure your code in a more intuitive and reusable way. Let’s explore the key concepts of OOP and how they are implemented in Python.

What is Object-Oriented Programming (OOP)?

Object-Oriented Programming is a programming paradigm based on the concept of “objects”, which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods or functions). Objects are instances of classes, which act as blueprints for creating objects.

Classes and Objects

In Python, everything is an object. A class is a blueprint for creating objects (instances), and an object is an instance of a class. Classes define the properties (attributes) and behaviors (methods) that objects of the class will have.

On the other hand, you can also create your own classes, which are known as user-defined classes.

Class names should start with a capital letter, followed by lowercase letters, if necessary. This is known as CamelCase notation.

Here’s a simple example of a user-defined class in Python:

class PlayerCharacter:
def __init__(self, name, age):
self.name = name #attribute
self.age = age #attribute

def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old."

# Creating objects (instances) of the PlayerCharacter
player1 #object = PlayerCharacter('Louie', 31)
player2 #object = PlayerCharacter('Fell', 28)

print(player1.name)
print(player2.age)


# Accessing attributes and calling methods
print(person1.name)
person1.greet()

In this example, PlayerCharacter is a class with attributes name and age, and a method greet that prints a greeting message.

The __init__ method in Python is a special method used for initializing newly created objects. It stands for "initialize" and is also known as the constructor method in object-oriented programming.

In this example, the __init__ method takes two parameters (name and age) along with the self parameter, which is a reference to the current instance of the class. Inside the __init__ method, we initialize the name and age attributes of the PlayerCharacter object using the values passed to the method.

The __init__ method can also have default values for parameters, allowing you to create objects with default attribute values if no values are provided.

The 4 pillars of OOP:

Encapsulation

Encapsulation is the bundling of data (attributes) with the methods that operate on that data. It restricts access to some of an object’s components, which can prevent the accidental modification of data.

Abstraction

Abstraction involves hiding the complex implementation details of a class and exposing only the necessary parts to the outside world. It allows programmers to focus on the essential features of an object while hiding irrelevant details.

*In Python, there isn’t a strict concept of private variables like in some other languages (e.g., Java or C++), where you can declare variables as private and restrict access to them outside the class. However, Python uses naming conventions to indicate that a variable or method should be treated as private.
By convention, variables or methods that start with an underscore
_ are considered private and should not be accessed from outside the class. While Python doesn't enforce this privacy, it's a strong indication to other developers that these elements are intended for internal use only.

Inheritance

Inheritance allows one class (subclass) to inherit attributes and methods from another class (superclass). It promotes code reuse and allows you to create a hierarchy of classes.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It allows methods to be written to manipulate objects of a base class to be used with objects of derived classes.

Example of Inheritance and Polymorphism:

# Parent class
class Movie:
def __init__(self, title, director):
self.title = title
self.director = director

def __repr__(self):
return f"Movie: {self.title}, Director: {self.director}"


# Child classes
class SciFi(Movie):
def __init__(self, title, director, films):
super().__init__(title, director)
self.films = films


class Action(Movie):
def __init__(self, title, director, volumes):
super().__init__(title, director)
self.volumes = volumes

# Polymorphism example
def __repr__(self):
return f"Movie: {self.title}, Volumes: {self.volumes}, Director: {self.director}"


# Creating instances of SciFi and Action
scifi1 = SciFi('Star Wars', 'George Lucas', 9)

action1 = Action('Kill Bill', 'Quentin Tarantino', 2)

# Calling a function with different objects
print(scifi1) # Output: Movie: Star Wars, Director: George Lucas
print(action1) # Output: Movie: Kill Bill, Volumes: 2, Director: Quentin Tarantino

In this example, both SciFi and Action classes inherit from the Movie class and implement the __repr__ method. The print function demonstrates polymorphism by allowing it to work with both objects.

Conclusion

Object-Oriented Programming is a powerful paradigm that allows for the creation of modular and reusable code. Understanding the basic principles of OOP, such as classes, objects, inheritance, encapsulation, and polymorphism, is essential for any Python programmer. Practice implementing these concepts in your own projects to deepen your understanding and improve your coding skills. In the next post, we will explore more advanced topics in Python, including First Class Objects, Higher Order Functions, and Decorators, building on the foundation laid by OOP.

--

--

Louie
0 Followers

Estudante de programação compartilhando seu aprendizado com intuito de ajudar outros iniciantes a alcançarem seus objetivos e aprenderem junto comigo.