Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

abc.abstractmethod

Il decoratore contrassegna un membro astratto nelle classi che usano ABCMeta.

Versione: Python 3.14; repository image, production runtime not attested

Sintassi

@property
@abstractmethod
def unit(self): ...

Il decoratore contrassegna un membro astratto nelle classi che usano ABCMeta.

abc.abstractmethod

Con property o classmethod, abstractmethod va posto più vicino a def. Il corpo astratto può fornire codice richiamabile tramite super() nella ridefinizione.

Base richiede unit e Scale estende la m di base restituendo mm.

from abc import ABC,abstractmethod
class Base(ABC):
    @classmethod
    @abstractmethod
    def make(cls): return cls()
assert Base.__abstractmethods__=={'make'}
class Concrete(Base):
    @classmethod
    def make(cls): return super().make()
assert type(Concrete.make()) is Concrete

Esempi

from abc import ABC, abstractmethod
class Base(ABC):
    @property
    @abstractmethod
    def unit(self): return "m"
class Scale(Base):
    @property
    def unit(self): return super().unit + "m"
print(sorted(Base.__abstractmethods__), Scale().unit)

Risultato

['unit'] mm

Base richiede unit e Scale estende la m di base restituendo mm.

Fonti