lundi 30 novembre 2020

Using one class to return different objects based on __init__() in Python?

I have to deal with two formats, say A and B. I want to build a class that handles these two formats in the best way possible in Python.

My idea was to have a class that based on what is passed on init() returns a different object responsible for handling that format. This way, my user has to deal with only one class.

class AnnotationHelper:
    
    def __init__(self, format):
        if format == "A":
           #return object AnnotationHelperA
        elif format == "B":
           #return object AnnotationHelperB 
        else raise ValueError("Invalid format")
    
   def get_x():
        raise NotImplementedError() //AnnotationHelperA and AnnotationHelperB should implement this

What would a "design pattern" like this be called? Is this a valid approach for my problem or is there another standard way of doing things like this? I just want my code to be as clean and re-usable as possible.

Aucun commentaire:

Enregistrer un commentaire