Welcome to the fundamental concepts of Object-Oriented Programming (OOP) in Python. Object-Oriented Programming is a paradigm that enables us to model real-world entities using objects, combining data and functionality in a structured and modular way. In this lesson, we’ll explore the core principles of OOP, understand classes and objects, and learn how to implement them in Python.

Basics of Object-Oriented Programming:

1. Definition:

2. Core Concepts:

3. Key Principles:

Classes and Objects in Python:

4. Defining a Class:

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

5. Creating Objects:

my_car = Car("Toyota", "Camry")

6. Class Attributes and Methods:

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def display_info(self):
        print(f"{self.make} {self.model}")

Example:

Let’s explore the Person class, representing individuals with attributes for name and age, and a method to display information.

# Example Code
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}")

# Creating objects (instances)
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# Accessing attributes and calling methods
person1.display_info()
person2.display_info()

Practice Exercise:

Let’s apply our knowledge by creating a Book class that represents books, including attributes for title, author, and year published, along with a method to display information.

# Example Practice Exercise
class Book:
    def __init__(self, title, author, year_published):
        self.title = title
        self.author = author
        self.year_published = year_published

    def display_info(self):
        print(f"Title: {self.title}, Author: {self.author}, Year Published: {self.year_published}")

# Creating objects (instances)
book1 = Book("Python Crash Course", "Eric Matthes", 2015)
book2 = Book("Clean Code", "Robert C. Martin", 2008)

# Accessing attributes and calling methods
book1.display_info()
book2.display_info()

Summary:

In this lesson, we’ve covered the essential concepts of Object-Oriented Programming (OOP) in Python. We’ve learned about classes, objects, attributes, and methods. Practice creating your own classes and objects to strengthen your understanding, and don’t hesitate to ask questions in the discussion forum. As we progress, we’ll delve deeper into advanced OOP topics, so let’s continue our exploration of Object-Oriented Programming principles!