Abstract Method Variants
Sveip for å vise menyen
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:
1234567891011121314151617181920212223242526272829303132from 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:
12345678910111213141516171819202122232425262728from 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:
123456789101112131415161718192021222324from 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.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår