Objects and class

Encapsulation and Inheritance

Abstraction and polymorphism

Object-oriented programming (OOP) is a style of programming characterized by the identification of classes of objects closely linked with the methods (functions) with which they are associated. It also includes ideas of inheritance of attributes and methods.

Object-oriented programming (OOP) is a way of thinking about and organizing code for maximum reusability.

With this type of programming, a program comprises objects that can interact with the user, other objects, or other programs. This makes programs more efficient and easier to understand.

OOP is a powerful tool for software development that helps developers to write clean, modular, and maintainable code. By organizing code into classes and objects, OOP allows developers to create software that is more efficient, reusable, and easier to maintain over time.


SUMMARY


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

    def say_hello(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

# Creating an object of the Person class
person1 = Person("John", 30)

# Accessing attributes of the object
print(person1.name) # Output: John

# Calling a method on the object
person1.say_hello() # Output: Hello, my name is John and I'm 30 years old.

  1. Inheritance:
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):
    def speak(self):
        return "Woof"

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

# Creating objects of the Dog and Cat classes
my_dog = Dog("Fido")
my_cat = Cat("Whiskers")

# Calling the speak() method on the objects
print(my_dog.speak()) # Output: Woof
print(my_cat.speak()) # Output: Meow

  1. Polymorphism:
class Shape:
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * (self.radius ** 2)

# Creating objects of the Rectangle and Circle classes
my_rectangle = Rectangle(4, 5)
my_circle = Circle(3)

# Calling the area() method on the objects
print(my_rectangle.area()) # Output: 20
print(my_circle.area()) # Output: 28.26