Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Abstract Classes and Blueprints | Наслідування
Об'єктно-орієнтоване програмування на Python

Abstract Classes and Blueprints

Свайпніть щоб показати меню

Abstract Base Classes (ABCs) are a powerful tool in Python for designing flexible and robust object-oriented systems. They help create maintainable code by defining clear contracts that subclasses must follow.

123456789101112131415161718192021222324
from abc import ABC, abstractmethod class PaymentMethod(ABC): @abstractmethod def pay(self, amount): pass class CreditCard(PaymentMethod): def pay(self, amount): return f"Paid {amount} using Credit Card" class PayPal(PaymentMethod): def pay(self, amount): return f"Paid {amount} using PayPal" def process_payment(method: PaymentMethod, amount): return method.pay(amount) print(process_payment(CreditCard(), 100)) print(process_payment(PayPal(), 250))

PaymentMethod is an abstract base class. It defines a required method, pay, that every payment type must implement. CreditCard and PayPal are concrete subclasses. They provide their own versions of the pay method, but follow the same interface.

Note
Note

The function process_payment works with any payment method because it relies on the shared abstract contract, not on specific classes.

question mark

What is the key difference between an abstract class and a concrete class?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 6

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 2. Розділ 6
some-alt