Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Abstract Method Variants | ABCs in Depth
Python Abstract Base Classes

Abstract Method Variants

Svep för att visa menyn

Abstract methods are not limited to regular instance methods. You can require subclasses to implement properties, class methods, and static methods using the correct combination of decorators. The modern approach differs from older deprecated decorators that you may still encounter in legacy code.

Abstract Properties

To require a subclass to implement a property, combine @property and @abstractmethod. @abstractmethod must be innermost:

1234567891011121314151617181920212223242526272829303132
from abc import ABC, abstractmethod # Requiring subclasses to implement a property class DatabaseConnection(ABC): @property @abstractmethod def connection_string(self): pass @property @abstractmethod def is_connected(self): pass class PostgresConnection(DatabaseConnection): def __init__(self, host, port, database): self._host = host self._port = port self._database = database self._connected = False @property def connection_string(self): return f"postgresql://{self._host}:{self._port}/{self._database}" @property def is_connected(self): return self._connected conn = PostgresConnection("localhost", 5432, "analytics") print(conn.connection_string) # "postgresql://localhost:5432/analytics" print(conn.is_connected) # False

Abstract Class Methods

Require subclasses to implement a class method using @classmethod and @abstractmethod:

12345678910111213141516171819202122232425262728
from abc import ABC, abstractmethod # Requiring subclasses to provide a factory class method class DataLoader(ABC): @classmethod @abstractmethod def from_config(cls, config): pass @abstractmethod def load(self): pass class CsvLoader(DataLoader): def __init__(self, filepath, delimiter): self._filepath = filepath self._delimiter = delimiter @classmethod def from_config(cls, config): return cls(config["filepath"], config.get("delimiter", ",")) def load(self): return f"Loading CSV from {self._filepath}" config = {"filepath": "/data/transactions.csv"} loader = CsvLoader.from_config(config) print(loader.load())

Abstract Static Methods

Require subclasses to implement a static method using @staticmethod and @abstractmethod:

123456789101112131415161718192021222324
from abc import ABC, abstractmethod # Requiring subclasses to provide a schema validator class ApiClient(ABC): @staticmethod @abstractmethod def validate_response(response): pass @abstractmethod def fetch(self, endpoint): pass class RestApiClient(ApiClient): @staticmethod def validate_response(response): return isinstance(response, dict) and "data" in response def fetch(self, endpoint): return {"data": f"results from {endpoint}"} client = RestApiClient() response = client.fetch("/transactions") print(RestApiClient.validate_response(response)) # True

Deprecated Decorators

The abc module originally provided @abstractproperty, @abstractclassmethod, and @abstractstaticmethod as dedicated decorators. These were deprecated in Python 3.3 and should not be used in new code:

You may still encounter the deprecated forms in older codebases – they still work but emit deprecation warnings.

question mark

What is the correct decorator order for an abstract class method?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 2. Kapitel 1
some-alt