Object-Oriented Programming (OOP)

Classes and Objects

Classes are blueprints for creating objects. Objects are instances of a class.

Example:

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

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

person1 = Person("Alice", 30)
print(person1.greet())  # Output: Hello, my name is Alice and I am 30 years old.

Inheritance

Inheritance allows a class to inherit methods and attributes from another class.

Example:

class Employee(Person):
    def __init__(self, name, age, position):
        super().__init__(name, age)
        self.position = position

    def describe_job(self):
        return f"I work as a {self.position}."

employee1 = Employee("Bob", 35, "Software Engineer")
print(employee1.greet())  # Output: Hello, my name is Bob and I am 35 years old.
print(employee1.describe_job())  # Output: I work as a Software Engineer.