Self-paced

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Full-Stack Software Developer - 16w

Data Science and Machine Learning - 16 wks

Search from all Lessons


LoginGet Started
← Back to Lessons

Weekly Coding Challenge

Every week, we pick a real-life project to build your portfolio and get ready for a job. All projects are built with ChatGPT as co-pilot!

Start the Challenge

Podcast: Code Sets You Free

A tech-culture podcast where you learn to fight the enemies that blocks your way to become a successful professional in tech.

Listen the podcast
  • object oriented programming

  • Python

Edit on Github

What is Object Oriented Programming?

Introduction to Object-Oriented Programming in Python
Object-Oriented Programming Basics

Introduction to Object-Oriented Programming in Python

Hello, future code master! In this lesson, we will explore the fascinating world of Object Oriented Programming (OOP). You will discover what OOP is and how this powerful technique allows you to create more organized, reusable, and maintainable programs.

Following we will see a small example of how to represent a person with a class of Python.

1class Person: 2 def __init__(self, name, lastname, age): 3 self.name = name 4 self.lastname = lastname 5 self.age = age 6 7 def presentation_message(self): 8 return f"¡Hi!, my name is {self.nombre} {self.apellido} and I am {self.edad} years old" 9 10person = Person("Thomas", "Smith", 27) 11print(person.presentation_message()) # output: ¡Hi!, my name is Thomas Smith and I am 27 years old.

This example shows how to represent a person using this style of object-oriented programming (OOP), to represent a real world object in a class. First, you must create a class with the name of that object, then within the class, you create the function __init__() and inside this function, you will create the properties of your object such as name, age, weight etc..., you may also create functions (methods) to manipulate the properties of the object.

What is Object Oriented Programming (OOP)?

Object Oriented Programming (OOP) is an approach to programming that is based on the idea of "objects". Instead of writing sequential lines of code, in OOP we create objects that represent real-world entities or abstract concepts. These objects contain both data (attributes) and functions (methods) that act upon that data. 🏰🔧

Object-oriented programming (OOP) is based on four main principles.

  1. Abstraction: We represent real world entities and concepts in the form of objects with attributes and methods.

  2. Encapsulation: We hide the internal details of the object and only expose an interface to interact with it.

  3. Inheritance: Objects can inherit attributes and methods from other objects, allowing the creation of class hierarchies.

  4. Polymorphism: Objects can use the same methods with different implementations.

Don't worry, we will explain each of these concepts in more detail later.

Classes and Objects: The Foundations of OOP

In OOP, we define the characteristics and behaviors of an object using a "class". A class is like a blueprint or template that describes how the object is created and what it can do. For example, we can have a class Dog with attributes like name and age, and methods like bark() and play(). 🐶

Next, we will create a class that represents a computer step by step, so that you can better understand how the concept of classes works in Python.

  1. First create a class using the reserved word class, then in this class create the necessary properties to represent a computer and the necessary methods to manipulate or extract these properties.
1class Computer: 2 def __init__(self, brand, price, color, cpu): 3 self.brand = brand 4 self.price = price 5 self.color = color 6 self.cpu = cpu 7 8 def obtain_information(self): 9 return { 10 "Brand": self.brand, 11 "Price": self.price, 12 "Color": self.color, 13 "CPU": self.cpu 14 }
  1. You can then create instances or objects based on that class. Each object is a separate entity with its own attribute values and can invoke the methods defined in the class.
1apple_computer = Computer("MacOS", 300_000, "Gray", "Apple M1") 2hp_computer = Computer("Hewlett-Packard HP", 200_000, "Blue", "Intel core i5") 3 4print("Apple: ", apple_computer.obtain_information()) 5print("HP: ", hp_computer.obtain_information())

output:

1Apple: { 2 'Brand': 'MacOS', 3 'Price': 300000, 4 'Color': 'Gray', 5 'CPU': 'Apple M1' 6} 7HP: { 8 'Brand': 'Hewlett-Packard HP', 9 'Price': 200000, 10 'Color': 'Blue', 11 'CPU': 'Intel core i5' 12}

As we can see in this example, you can represent two different computers using the same object/class, every time you create a new instance of that class, the method obtain_information() will return the values of that instance of the class, so we avoid the need to repeat unnecessary code to represent different objects, this is very useful when you need to represent many elements as for example in e-commerce.

Object-Oriented Programming Basics

As mentioned before, object-oriented programming (OOP) is based on four fundamental concepts, below we will see each of them in more detail and code examples that will help you understand them better.

Abstraction

Abstraction is a very important concept in (OOP) that allows to represent real world objects in a program through the use of classes and objects. Basically abstraction allows you to represent a particular type of real or abstract object such as a person, a household appliance, or an animal, to be used in a program.

Inheritance

Object/class inheritance in object-oriented programming is a fundamental concept, allows you to create a new class based on an existing class. The existing class is known as a base class or superclass, and the created class is known as a derivative class or subclass.

Example:

1class Person: 2 def __init__(self, name, lastmame, citizenship): 3 self.name = name 4 self.lastname = lastname 5 self.citizenship = citizenship 6 7 def obtain_complete_name(self): 8 return f"{self.name} {self.lastname}" 9 10class Programmer(Person): 11 def __init__(self, name, lastname, citizenship, salary, company): 12 super().__init__(name, lastname, citizenship) 13 self.salary = salary 14 self.company = company 15 16person = Person("Axel", "Castro", "Mexican") 17programmer = Programmer("Thomas", "Smith", "United States", 800_000, "Google") 18 19print(person.obtain_complete_name()) # output: Axel Castro 20print(programmer.obtain_complete_name()) # output: Thomas Smith

In this example, the class Person allows you to represent a person with his or her basic characteristics, then the class Programmer can inherit the characteristics of the class Person and add to it the other characteristics that represent a programmer, it can be said that the programmer class is a child class of the class Person and you can use the properties and methods itself as you can see in the example, with method obtain_complete_name(). You must use the following syntax, for a class to inherit the properties and methods of another class class new_class(parent_class), it is also very important that within the function __init__() you pass on the function super().__init__() with the properties of the parent class, so that you can use its properties in the new child class.

3. Encapsulation

Encapsulation is also a very important concept in OOP, it is a way to hide the internal implementation of a class by allowing only some specific attributes and methods to be directly accessible. You can understand encapsulation, as the ability of a class to allow access to its attributes by declaring them as public or private. In Python naming conventions are used to indicate the visibility of its members, if an attribute or method has a name that begins with two underscores (__) it is considered highly private.

Example:

1class House: 2 def __init__(self, square_area, place, price): 3 self.square_area = square_area 4 self.place = place 5 self.__price =price 6 7 def get_price(self): 8 return self.__price 9 10 def set_price(self, value): 11 self.__price = value 12 13new_house = House(100_000, "México", 700_000_000) 14 15print(new_house.__price) # output: 'House' object has no attribute '__price'. Did you mean: 'get_price'? 16print(new_house.get_price()) # output: 700000000 17 18new_house.__price = 500_000_000 # Does not allow you to modify the __price property 19print(new_house.get_price()) # output: 700000000 20 21new_house.set_price(400_000_000) 22print(new_house.get_price()) # output: 400000000

As you can see in the example, in the class House the properties square_area and placeare public properties which you can access without any problem, but the property __price on the other hand, is a private property and you cannot access it directly, in order to access or modify a private property you must use the Getter and Setter functions. get_price(), set_price() are conventions in object-oriented programming, the get and set methods are used to obtain or modify private properties within the class.

4. Polymorphism

Finally, polymorphism is another fundamental concept in object-oriented programming. In simple terms, polymorphism allows different classes to behave similarly, but with specific implementations for each one.

Example:

1class Car: 2 def __init__(self, brand, model): 3 self.brand = brand 4 self.model = model 5 6 def obtain_model(self): 7 pass 8 9class Family_car(Car): 10 def __init__(self, brand, model): 11 super().__init__(brand, model) 12 13 def obtain_model(self): 14 return f"The family car is model: '{self.model}'" 15 16class Sport_car(Car): 17 def __init__(self, brand, model): 18 super().__init__(brand, model) 19 20 def obtain_model(self): 21 return f"The sport car model '{self.model}' is the most recent" 22 23family_car = Family_car("Ford", "Familiar 2023") 24sport_car = Sport_car("Tesla", "Tesla motors sport") 25 26print(family_car.obtain_model()) # output: The family car is model: 'Familiar 2023' 27print(sport_car.obtain_model()) # output: The sport car model 'Tesla motors sport' is the most recent

Polymorphism is based on the ability of an object/class to adopt different forms, in the example above the method obtain_model() of the abstract class Car is used in different forms in classes Family_car and Sport_car returning different messages each. This is a short example of the concept of polymorphism, the ability to use the same function of a class in different ways.

Advantages of Object-Oriented Programming 🌟💼

OOP offers multiple advantages that make programming more efficient and effective:

  • Code Reuse: With OOP, you can reuse existing classes and objects to create new programs, which saves time and effort.

  • Simplified Maintenance: Encapsulation allows you to modify a class without affecting the rest of the program, facilitating maintenance and avoiding unwanted side effects.

  • Organization and Clarity: The OOP promotes a clear and organized structure in the code, which makes it easier to read and understand.

  • Real World Modeling: OOP allows you to model real-world entities and processes in a natural way, which makes code more intuitive.

Object Oriented Programming (OOP) is a fundamental technique that allows you to create more organized, reusable, and maintainable programs. Now that you have a basic understanding of OOP, you can start creating your own classes and objects to bring your projects to life! If you want to learn more about this programming language I invite you to read the following Python tutorial in 4Geeksblog.

Code will set you free ✨👨‍💻