DEV Community

KENNEDY NDUNGU WANJIRU
KENNEDY NDUNGU WANJIRU

Posted on

Mastering OOP in Python Without the Headache

You know lists, dictionaries, loops, functions and control flows. You stared at class Dog: and def __init__(self, name): and wondered whether you have by mistake opened a Java tutorial.
Once you understand a few concepts, you will find that you have been using OOP in Python all the time. You will see that it is straightforward and intuitive - a natural extension to your Python knowledge.Object oriented programming has 4 pillars and they are
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

Classes in OOP are like blueprints or templates for creating objects. An object is a specific instance of a class, containing attributes and behaviors defined in the class. For instance, if a class represents the concept of a 'tree', then each 'tree' planted is an object of that class, with its own unique characteristics.

Imagine a forest with various tree species. Each species has unique characteristics like height, age, and species type. We can model this diversity using a class for trees, where each tree object represents a specific tree in the forest.
In this article, we explore the basic concepts of OOP using Python code examples. We will learn about classes, instances, inheritance and dunder methods.

An object oriented programming start with a class,a class is created using the keyword class and the name of the class folllowed by a fullcolon :.Follow it by a constructor method to initialise class attributes the method should end in fullcolon.Attributes are variables stored on the object like self.name.self refers to the specific instance being created or used. It must be the first parameter of instance methods.
A method is simply a function defined inside a class. It describes what objects of that class can do.We can create as many methods as we want in a class.

Encapsulation is a fundamental OOP principle that involves bundling data (attributes) and methods (functions) that operate on the data into a single unit or class. It also restricts direct access to some of the object's components, which is a means of preventing accidental interference and misuse of the data.



Im

The Tree class in the code defines a blueprint for creating tree objects with specific attributes: species, height, and age. The __init__ method, known as the constructor, initialises these attributes when a new tree object is created. The describe method provides a simple way to output a description of the tree, demonstrating how methods can operate on the data encapsulated within the same object, allowing for clear and maintainable code structures.
In our Tree class, encapsulation is demonstrated by how the attributes (species, height, age) and the method (describe) are enclosed within the class. This design allows us to create tree objects with their properties and behaviors neatly packaged together.
Once we have a class ready we need to create an instance,an instance is a concrete object built from that blueprint.To get an object call the class like a function.
Ima

This example shows how encapsulation makes our code more manageable and secure. By keeping the data (attributes like species, height and age) and methods (describe) within the class, we maintain a structured and organised approach to coding, which is particularly helpful in complex programming scenarios.

Inheritance in OOP allows us to define a class that inherits all the methods and properties from another class. The parent (or base) class is the class being inherited from, and the child (or derived) class is the class that inherits from the parent class.


Imagine a tree ecosystem where we have a Tree class as our base class with attributes like species, age, and height, and methods grow() and reseed(). From this base class, we derive two subclasses: Oak and Pine.

The Oak class inherits the properties and methods from Tree and adds its own method budding(). Similarly, the Pine class inherits from Tree and adds a cone_count() method.

Ima

The Oak and Pine classes illustrate inheritance by reusing the code from the Tree class. They also demonstrate how we can extend the functionality of a base class by adding new methods that are specific to the subclass. This not only saves time by not having to rewrite shared code but also helps maintain a natural and understandable hierarchy within the codebase, mirroring real-world relationships.

**Polymorphism **in OOP allows objects of different classes to respond to the same message—or method call—in ways appropriate to their types. This means that the same method can behave differently in different classes.


Let's say we have two subclasses, Oak and Pine, that stem from the same parent class Tree. Each subclass can respond to common messages like grow() and reseed(). However, due to polymorphism, when the grow() signal is sent, both Oak and Pine trees will grow, but the way they grow and how much they grow can vary. When the reseed() signal is sent, both types of trees will disperse seeds, but the types of seeds and the method of dispersal might be different. Furthermore, each type of tree may have additional processes that are unique to its kind, such as budding() in Oaks or cone_count() in Pines.
Im
Ima

Abstraction in OOP is the concept of hiding the complex reality while exposing only the necessary parts. It's like using a simple user interface (UI) that hides the complex code behind it. For example, we often log in to websites via simple UIs, which abstracts us from the complex code.



Let's say we want to provide a simple interface for the growth of various types of trees without needing to understand the intricate details of how each tree grows. The Tree class will represent the abstract concept of a tree with the method grow(), which is an abstract method because it's not implemented. Specific types of trees, such as EvergreenTree, will provide concrete implementations of the grow() method.
For abstraction to work we have to import abstractmethod into our code.

Ima

The Tree class serves as an abstract base class, similar to the user-friendly login interface. It defines the structure and expectations (like the login fields) without detailing the specifics. The EvergreenTree class extends Tree and provides the specifics of how an evergreen tree grows. This hides the complexity from the user, who simply needs to know that they can make a tree grow by calling the grow() method, much like a user only needs to enter a username and password and click 'login' to start a session. This abstraction makes the code easier to use and maintain, as well as to extend with new types of trees.
I hope this article helps you understand object oriented programming.

Top comments (0)