Mastering Object-Oriented Programming in Python: Core Concepts with Practical Examples

allglenn
3 min readNov 24, 2023

Object-Oriented Programming (OOP) in Python is a programming paradigm that uses “objects” and their interactions to design applications and computer programs. It’s a way to structure and organize your code. Let’s dive into the core concepts of OOP in Python with examples:

Classes and Objects

  • Classes: Think of a class as a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).
  • Objects: An instance of a class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
return "Woof!"

# Create an instance of Dog
my_dog = Dog("Buddy", 3)
print(my_dog.bark()) # Outputs: Woof!

Inheritance

  • It allows new objects to take on the properties of existing objects.
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

class Cat(Animal):
def speak(self):
return "Meow"

my_cat = Cat("Whiskers")
print(my_cat.speak()) # Outputs: Meow

Encapsulation

  • The bundling of data, and the methods that operate on that data, into a single unit.
class Computer:
def __init__(self):
self.__max_price = 900 # private variable

def sell(self):
return f"Selling Price: {self.__max_price}"

def set_max_price(self, price):
self.__max_price = price

c = Computer()
print(c.sell()) # Outputs: Selling Price: 900

# Change the price
c.set_max_price(1000)
print(c.sell()) # Outputs: Selling Price: 1000

Polymorphism

  • The ability to present the same interface for differing underlying data types.
class Parrot:
def fly(self):
return "Parrot can fly"

def swim(self):
return "Parrot can't swim"

class Penguin:
def fly(self):
return "Penguin can't fly"

def swim(self):
return "Penguin can swim"

# common interface
def flying_test(bird):
return bird.fly()

# instances
parrot = Parrot()
penguin = Penguin()

print(flying_test(parrot)) # Outputs: Parrot can fly
print(flying_test(penguin)) # Outputs: Penguin can't fly

Method Overriding

  • It’s when a method in a subclass uses the same name as a method in its superclass but provides a specific implementation for it.
class Parent:
def myMethod(self):
return "Calling parent method"

class Child(Parent):
def myMethod(self):
return "Calling child method"

c = Child()
print(c.myMethod()) # Outputs: Calling child method

Apart from the core OOP concepts, there are several other useful concepts in Python programming that enhance the way we work with classes and objects. Here are some of them, along

Class Variables and Instance Variables

  • Class Variables: Shared among all instances of a class.
  • Instance Variables: Unique to each instance.
class Employee:
# Class variable
raise_amount = 1.04

def __init__(self, first, last, pay):
# Instance variables
self.first = first
self.last = last
self.pay = pay

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)

emp1 = Employee('John', 'Doe', 50000)
emp2 = Employee('Jane', 'Doe', 60000)

# Apply raise
emp1.apply_raise()
print(emp1.pay) # Outputs: 52000

Static Methods and Class Methods

  • Static Methods: Behave like plain functions but belong to the class’s namespace.
  • Class Methods: Work with the class since its parameter is always the class itself.
class MyClass:
@staticmethod
def my_static_method():
return "This is a static method"

@classmethod
def my_class_method(cls):
return f"This is a class method of {cls}"

print(MyClass.my_static_method()) # Outputs: This is a static method
print(MyClass.my_class_method()) # Outputs: This is a class method of <class '__main__.MyClass'>

Property Decorators — Getters, Setters, and Deleters

  • Used to get, set, and delete the value of a property using methods as if they were attributes.
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name

@property
def email(self):
return f"{@email.com">self.first_name}.{self.last_name}@email.com"

@property
def fullname(self):
return f"{self.first_name} {self.last_name}"

@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first_name = first
self.last_name = last

person = Person("John", "Smith")
person.fullname = "Corey Schafer"
print(person.first_name) # Outputs: Corey
print(person.email) # Outputs: Corey.Schafer@email.com

Magic/Dunder Methods

Special methods which have double underscores (dunder) at the beginning and the end of their names. They are used for operator overloading and customizing the behavior of Python classes.

class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages

def __str__(self):
return f"{self.title} by {self.author}"

def __len__(self):
return self.pages

book = Book("Python Programming", "John Doe", 300)
print(book) # Outputs: Python Programming by John Doe
print(len(book)) # Outputs: 300

Iterators and Generators

  • Iterators are objects that can be iterated upon. Generators yield a sequence of values lazily, pausing after each one until the next one is requested.
def countdown(num):
while num > 0:
yield num
num -= 1

for count in countdown(5):
print(count)
# Outputs: 5 4 3 2 1

--

--

allglenn

👋 Hi, I’m @allglenn 👀 I’m a tech bro in paris 🗼🇫🇷 I’m currently learning about aws,saas,nodejs,Terraform,React ,AI,ML and any kind of innovation