Object-oriented Programming (OOP)

Object-oriented Programming (OOP) is a programming paradigm in Python that focuses on creating and organizing code into objects, which are instances of classes. OOP allows you to model real-world entities, abstract data, and their interactions in a more structured and modular way. This tutorial provides an overview of object-oriented programming in Python, including classes, objects, inheritance, and encapsulation.

Classes and Objects

In OOP, a class is a blueprint or template that defines the structure and behavior of objects. An object is an instance of a class, representing a specific entity with its own attributes and methods.

Creating a Class

To create a class in Python, you use the class keyword followed by the class name and a colon.


      class Dog:
          # Class attributes and methods defined here
          pass
      

Creating an Object

To create an object of a class, you call the class as if it were a function.


      # Creating an instance of the Dog class
      my_dog = Dog()
      

Attributes and Methods

Attributes are variables that belong to the class or object, representing the data associated with them. Methods are functions defined within a class, used to perform actions on objects.

Adding Attributes and Methods


      class Dog:
          # Class attribute
          species = "Canine"

          # Method to initialize the object with a name
          def __init__(self, name):
              self.name = name

          # Method to make the dog bark
          def bark(self):
              return "Woof!"
      

Accessing Attributes and Methods


      # Creating an object of the Dog class
      my_dog = Dog("Buddy")

      # Accessing the class attribute
      print(my_dog.species)  # Output: "Canine"

      # Accessing the instance attribute
      print(my_dog.name)  # Output: "Buddy"

      # Calling the object's method
      print(my_dog.bark())  # Output: "Woof!"
      

Inheritance

Inheritance allows you to create a new class based on an existing class, inheriting its attributes and methods. The new class is called the subclass, and the existing class is called the superclass.


      class Poodle(Dog):
          # Additional method(s) specific to the Poodle class
          def dance(self):
              return f"{self.name} is dancing!"
      

Encapsulation

Encapsulation is the concept of hiding the internal details of a class from the outside. It is achieved by using private attributes and methods.


      class Car:
          def __init__(self):
              # Private attribute
              self.__mileage = 0

          def drive(self, distance):
              # Private method
              self.__mileage += distance