Saturday, July 6, 2024

Object-Oriented Programming (OOP) concepts in Python

 Let's explain Object-Oriented Programming (OOP) concepts in Python 

1. **Classes and Objects** πŸ“¦πŸ•


- **Class**: A blueprint for creating objects.

  ```

  class Dog:  # πŸ“¦

      def __init__(self, name, age):

          self.name = name

          self.age = age

  ```


- **Object**: An instance of a class.

  ```

  my_dog = Dog("Buddy", 3)  # πŸ•

  ```


2. **Attributes and Methods** πŸ”§πŸ“œ


- **Attributes**: Variables that belong to a class or an instance.

  ```

  class Dog:

      species = "Canis lupus familiaris"  # 🧬 Class attribute


      def __init__(self, name, age):

          self.name = name  # πŸ“› Instance attribute

          self.age = age

  ```


- **Methods**: Functions defined inside a class.

  ```

  class Dog:

      def bark(self):  # πŸ”Š Instance method

          print(f"{self.name} says Woof!")

  ```


3. **Inheritance** πŸ‘¨‍πŸ‘¦πŸΎ


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

  ```

  class Animal:  # πŸ‘¨‍πŸ‘¦

      def __init__(self, species):

          self.species = species


  class Dog(Animal):  # 🐾

      def __init__(self, name, age):

          super().__init__("Canine")

          self.name = name

          self.age = age

  ```


4. **Encapsulation** πŸ”’πŸ“₯


Encapsulation is the bundling of data and methods within one unit, restricting direct access to some components.

  ```

  class Dog:

      def __init__(self, name, age):

          self._name = name  # πŸ”’ Protected attribute

          self.__age = age   # πŸ”’ Private attribute


      def get_age(self):  # πŸ“₯

          return self.__age


      def set_age(self, age):

          if age > 0:

              self.__age = age

  ```


5. **Polymorphism** πŸŽ­πŸ› ️


Polymorphism allows different classes to be treated as instances of the same class through a common interface.

  ```

  class Animal:

      def make_sound(self):  # 🎭

          pass


  class Dog(Animal):

      def make_sound(self):  # πŸΆπŸ”Š

          print("Woof!")


  class Cat(Animal):

      def make_sound(self):  # πŸ±πŸ”Š

          print("Meow!")


  def animal_sound(animal):  # πŸ› ️

      animal.make_sound()

  ```


6. **Abstraction** πŸ•΅️‍♀️πŸ”


Abstraction means hiding complex implementation details and showing only the necessary features.

  ```

  from abc import ABC, abstractmethod


  class Animal(ABC):  # πŸ•΅️‍♀️

      @abstractmethod

      def make_sound(self):  # πŸ”

          pass


  class Dog(Animal):

      def make_sound(self):  # πŸΆπŸ”Š

          print("Woof!")

  ```

No comments:

AI's Impact on the IT Industry 2026