Abstract Base Classes

Intermediate Object-Oriented Programming in Python

Jake Roach

Data Engineer

Abstract base classes

Abstract base classes क्लासों के लिए एक ब्लूप्रिंट बनाती हैं, जहाँ ऐसी abstract methods तय की जाती हैं जिन्हें सभी चाइल्ड क्लासेस में लागू करना जरूरी है.

  • क्लासों के समूह में कॉमन व्यवहार सुनिश्चित करता है
  • @abstractmethod डेकॉरेटर
  • इन्हें inherit किया जाता है, instantiate नहीं
  • Abstract base class की सभी methods का abstract होना जरूरी नहीं (concrete methods हो सकती हैं)
class School:
    # Do things such as enroll 
    # and add a course
class MiddleSchool:
    # Play an instrument, join a club
    # but must enroll and add courses
class HighSchool:
    # Play a varsity sport, apply
    # for college, but must enroll 
    # and add courses
Intermediate Object-Oriented Programming in Python

एक abstract base class बनाना

from abc import ABC, abstractmethod

# Create an abstract base class that inherits # from ABC class School(ABC): @abstractmethod def enroll(self): # This method must be implemented # in classes that inherit from it pass
# Concrete methods are inherited def graduate(self): print("Congrats on graduating!")
  • abc मॉड्यूल की ABC क्लास से inherit करें
  • pass
  • जो भी क्लास School से inherit करे, उसे enroll() implement करनी होगी
  • Concrete methods भी रख सकते हैं
Intermediate Object-Oriented Programming in Python

Abstract base classes को implement करना

class HighSchool(School):
    def enroll(self):
        print("Welcome to high school!")

# Create an instance of HighSchool
high_school = HighSchool()
high_school.enroll()
Welcome to high school!
high_school.graduate()
Congrats on graduating!
  • HighSchool को enroll() method ज़रूर परिभाषित करनी होगी
  • यदि enroll() परिभाषित नहीं है तो TypeError
  • HighSchool, graduate() method inherit करता है
Intermediate Object-Oriented Programming in Python

एक से अधिक abstract methods

class School(ABC):
    @abstractmethod
    def enroll(self):
        pass

    @abstractmethod
    def add_course(self, course_name):
        pass

    def graduate(self):
        print("Congrats on graduating!")

  • दो abstract methods: enroll() और add_course()
class HighSchool(School):
    def __init__(self):
        self.courses = []

    # Implementing abstract method
    def enroll(self):
        print("Welcome to high school!")

    # Implementing abstract method
    def add_course(self, course_name):
        self.courses.append(course_name)
        print(f"You enrolled in {course_name}")

Intermediate Object-Oriented Programming in Python

अभ्यास करते हैं!

Intermediate Object-Oriented Programming in Python

Preparing Video For Download...