DEV Community

An Vo
An Vo

Posted on

Python OOP

I. What is Python OOP?

OOP = Object Oriented Programming.

  • Python fully supports OOP with Class and Class Inheritance. A Python class is a blueprint for creating from 1 to many objects. It can have:
  • Attributes are attached to it to maintain its state. They may be read-only or writeable.
  • Methods to modify its state. Syntax to define a class name "Animal":
class Animal:
    def __init__(self, secret_attribute="Suyt"):
        # __init__: constructor that runs when an object is created.
        # self: refers to the current instance of the class
        self.num_eyes = 2
        self.__secret_attribute = secret_attribute # Private variable

    def breathe(self):
        print("Inhale, exhale.")

    def get_secret_attribute(self):
        return self.__secret_attribute

    def make_sound(self):
        pass  # To be implemented by subclasses
Enter fullscreen mode Exit fullscreen mode

II. What are the core concepts or elements of OOPs?

  • Class: a blueprint for creating objects class Animal
  • Object: an instance of a class. Instantiation is an action that creates an instance from the class nemo_fish = Fish().
  • Encapsulation: restricted direct access to attributes or from the outside self.__secret_attribute

  • Inheritance: Allows a child class to use methods and properties from parents' classes.

class Fish(Animal):
    """Fish class is an inheritance from Animal"""
    def __init__(self):
        super().__init__() # call Animal init

    def breathe(self):
        super().breathe() #call the Animal breathe function, then modify it.
        print("doing this underwater.")

    def swim(self):
        print("moving in the water")

Enter fullscreen mode Exit fullscreen mode
  • Polymorphism: allows different classes to use the same method name but different implementations.
class Dog(Animal):
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

animals = [Dog(), Cat()]
for animal in animals:
    print(animal.make_sound())  # Calls the correct method based on the object type
Enter fullscreen mode Exit fullscreen mode
  • Abstraction: hiding implementation details and only exposing essential functionalities. For example: we have many 2 kinds of animals: cats, dogs, and fish. We know they care how they make the sound, only care that they can make a sound.
from abc import ABC, abstractmethod # import abstract base class module

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

# Getting error if instantiate an abstract class
# dog = Animal()
# TypeError: Can't instantiate abstract class Animal
# without an implementation for abstract method 'make_sound'

# Dog class inherits from Animal so it has to implement method make_sound
class Dog(Animal):
    def make_sound(self):
        return "Woof! Woof!"

perfect_dog = Dog()
print(perfect_dog.make_sound())
# Woof! Woof!
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post