Object-Oriented Programming (OOP) in Python

Introduction — What is Object-Oriented Programming in Python

Nima Javan
5 min readMar 24, 2024

Object-Oriented Programming is a programming paradigm that structures programs so that properties and behaviors are tied into individual objects.

For example, an object could represent a car with properties like a make, model, and year manufactured and behaviors like driving, parked, and drifting. Another example would be a dog with properties like sleeping, eating, and walking and behaviors like barking and panting.

In other words, object-oriented programming is a way for displaying detailed, real-world applications, like cars as well as relations between things, like restaurants and chefs or professors and students. OOP models real-world applications as objects that have soma data related with them and can perform certain operations.

Objects are at the center of object-oriented programming (hence the name). In other programming paradigms, object only represent chunks of data. In OOP, not only do they represent data but they additionally inform the overall structure of the program.

The 4 Pillars of OOP in Python

  • Abstraction — the ability to hide the implementation details of an object from the user
  • Encapsulation — the practice of combining data and methods within a class to protect the data from external interference
  • Inheritance — create new classes based on existing ones, allowing the new classes to inherit the attributes and methods of the parent class
  • Polymorphism — objects of different classes to be treated as if they were of the same class

How To Define a Class in Python

In Python, you define a class by using the ‘class’ keyword followed by a name, starting with a capital letter, for the class and a colon. Following that, you create a method using the ‘def’ keyword followed by ‘__init__()’ to declare which attributes each instance of the class should have.

Example:

class Motorcycle:
def __init__(self, make, model):
self.make = make
self.model = model

In the code above, you can see there’s a lot going on, but what does it all mean? From what what we can grasp at first glance, we can see that the class name is ‘Motorcycle’. The code defines the Motorcycle class with an __init__ method. The __init__ method is like a default constructor in C++ and Java. They are built into Python’s language and there are a vast amounts of built in constructors each with different purposes. One of the most important ones being the ‘__init__’ method. What does it do? Let’s take a step back. Constructors are used to initialize the object’s state. The __init__ method’s purpose is ‘initialize’ (hence the abbreviated name) or assign values to the data holders of the class when an object of the class is created. The method takes an object as its first argument (self), which is later followed by any additional arguments that need to be passed to, if there is any. Revisiting to the example above, we see that the __init__ method is taking two parameters, ‘make’ and ‘model’, and assigns them to the corresponding attributes of the class instance.

Class vs. Instances

Classes enable the user to create user-defined data structures. Classes later are followed by functions called methods, which targets the actions and behaviors that an object created from the class can perform with its data. Think of classes as a blueprint for how to define something. The class itself doesn’t hold any data but an object’s instance that’s built from a class withholds data. For example, think of the class as a survey. An instance are the answers to those questions that you’ve written down. Just how other people can fill out the same survey and every response is unique to them, you can create many instances from a single class.

How To Instantiate a Class

Instantiating a class is when you create a new object from a class. You can create a new object by typing the class name followed by parentheses:

class Food:
pass

Food()

Firstly, you create a new Food class with no attributes or methods, and then you instantiate the ‘Food’ class to create a Food object. The pass keyword under tells Python to neglect the class, without the pass keyword, it would run as an empty class and return an error.

Example:

food_1 = Food()
food_2 = food()

The code above displays the creation of unique instances of the ‘Food’ class. To assign data to the these instances above, we would be using instance variables. Instance variables hold data that is unique to that instance. To create this we would do the following:

food_1.name = 'Pizza'
food_1.origin = 'Italy'
food_1.price = '$15'

This method is deem to be suboptimal, imagine if we had to code 1000 employees. Trying to create and set that many variables increases time but also means a high risk of code and errors. Thankfully, with the built-in ‘__init__’ method, we are able to create instances automatically.

def __init__ (self, name, origin, price, menu):
self.name = name
self.origin = origin
self.price = price
self.menu = self.name + ' For Sale: ' + self.price

With that being completed, when we create a food, the instance would be passed in automatically, and the only thing we are left with is to price the food’s attributes.

food_1 = Food('Pizza','Italy','$15')
food_2 = Food('Hamburger','United States','$10')

Running this script ‘food_1’ would be passed into the ‘__init__’ method as ‘self’. Now let’s say we want to display the name and price of the food. We could use the format function in python to concatenate strings to get the food’s description. Problem with this is it would require doing this every time we want to print the food’s description. A more optimal approach to be advantageous of code re-use, we would be creating a method to help us generate each food’s description.

def fooddescription(self):
return self.name + ' ' + self.origin

That completes it for class and instance of a class creation. Now let’s put the full source together:

class Food:

def __init__(self, name, origin, price, menu):
self.name = name
self.origin = origin
self.price = price
self.menu = self.name + ' For Sale: ' + self.price

def fooddescription(self):
return self.name + ' ' + self.origin

food_1 = Food('Pizza','Italy','$15')
food_2 = Food('Hamburger','United States','$10')

print (food_1.menu)
print (food_2.menu)

print (food_1.fooddescription()) #or (Food.fooddescription(food_1))

In conclusion, Object-oriented programming is a set of concepts and patterns programmers use to solve problems with objects. An object is a single collection of data, also referred to as attributes, and behavior (methods).

--

--