Module 9 of 15 · Python for AI — Complete Beginner Course · Beginner

Object-Oriented Programming (OOP)

Duration: 5 min

OOP is a programming paradigm that organizes code into objects and classes. It helps you write more organized, reusable, and maintainable code.

Classes and Objects

A class is a blueprint for creating objects. An object is an instance of a class. Think of a class as a cookie cutter and objects as the cookies.

# Define a class
class Dog:
    # Constructor - runs when object is created
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # Method
    def bark(self):
        return f"{self.name} says Woof!"
    
    def get_age(self):
        return f"{self.name} is {self.age} years old"

# Create objects (instances)
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

# Call methods
print(dog1.bark())        # 'Buddy says Woof!'
print(dog1.get_age())     # 'Buddy is 3 years old'
print(dog2.bark())        # 'Max says Woof!'

Try it in Google Colab: Open in Colab

Buddy says Woof!
Buddy is 3 years old
Max says Woof!

Inheritance

Inheritance allows a class to inherit properties and methods from another class. This promotes code reuse and establishes relationships between classes.

Learn more: https://docs.python.org/3/tutorial/

# Parent class
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return f"{self.name} makes a sound"

# Child class
class Dog(Animal):
    def speak(self):
        return f"{self.name} barks"

class Cat(Animal):
    def speak(self):
        return f"{self.name} meows"

# Create objects
dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak())  # 'Buddy barks'
print(cat.speak())  # 'Whiskers meows'
Buddy barks
Whiskers meows

💡 Tip: Use inheritance to avoid code duplication. Child classes inherit all methods from parent.

❓ What is the purpose of __init__?

# Advanced example for Object-Oriented Programming (OOP)
# Production-ready pattern
print('Advanced implementation')
Advanced implementation

❓ What is a best practice when working with Object-Oriented Programming (OOP)?

💡 Tip: Pro Tip: Master Object-Oriented Programming (OOP) thoroughly before moving to advanced topics. This foundation is crucial for writing professional Python code.

← Previous Continue interactively → Next →

Related Courses