dimanche 21 novembre 2021

Decorator class for all subclasses of a class

I'm using a library with classes that all inherit from one super class, and the methods in each subclass return objects with the same keys, for example

class Store:

    def check_schedule(self, name):
        return

    def check_inventory(self, product):
        return


class Bakery(Store):

    def check_schedule(self, name):
        # Some unique code to Bakery
        return {
            'name': '...',
            'hours': '...',
            'maxHours': '...',
        }

    def check_inventory(self, product):
        # Some unique code to Bakery
        return {
            'amount': '...',
            'price': '...',
        }


class Tools(Store):

    def check_schedule(self, name):
        # Some unique code to Tools
        return {
            'name': '...',
            'hours': '...',
            'maxHours': '...',
        }

    def check_inventory(self, product):
        # Some unique code to Tools
        return {
            'amount': '...',
            'price': '...',
        }

I want to add a decorator subclass to some of the methods to manipulate response data, and I want this decorator on every subclass. For example, if I wanted to convert the responses to German, this decorator would look like

class GermanStore(Tools or Bakery):

    def translate(self, object):
        # convert object to German
        return object

    def check_schedule(self, name):
        returnObject = super().check_schedule(name)
        return self.translate(returnObject)

    def check_inventory(self, product):
        returnObject = super().check_schedule(product)
        return self.translate(returnObject)

Is this possible? Is there a name for this type of architecture pattern?


The answer does not need to be python specific, but I am using python, so the feature would need to be available in python for the answer to be useful

Aucun commentaire:

Enregistrer un commentaire