[Python] How to properly implement instantiation of an abstract class based on parameters

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create a class that is called from other methods and change the implementation of that class based on some context (like params):

    Abstract class:

    class PdfRenderer(ABC):
    # Something else ...

    @abstractmethod
    def render(self, filename: str):
    raise NotImplementedError("Subclasses should implement this method")


    Implementation:

    class ReportlabRenderer(PdfRenderer):
    # Some other implementations

    def __init__(self, data: CertificateData, image_path: str, hash: str):
    ...

    @override
    def render(self, filename: str | IO[bytes]):
    ...


    Calling method, but this is not what I want:

    def render_and_send_pdf(self):
    ...
    ReportlabRenderer(data, image_path, self.request.id).render(temp_file)
    ...


    Instead, I want the calling method to look something like this:

    def render_and_send_pdf(self):
    ...
    PdfRenderer(<params>).render(temp_file)
    ...


    The resolution of which renderer to use should be residing somewhere inside the PdfRenderer class where the other methods are unaware of the exact implementation and they have a nice abstract interface to call. How can I achieve that?

    Continue reading...

Compartilhe esta Página