jeudi 18 mars 2021

Pythonic Way to Create an 'Append-able' Base Class

I want to create a base class that has two 'mapping' attributes in the form of dictionaries and some static functions. In my use case, I envision the customization in the subclasses would be additive, meaning, they would use the existing mappings but also add more to the dictionaries. What is the best, most Pythonic way to do this? It's easy enough to overwrite attributes/methods in subclasses but I'm struggling to think of an elegant way to extend them.

i.e.,

class ExampleBaseClass():
    def __init__(self):
        self.map1 = {"a": 1, "b": 2}
        self.map2 = {"cow": "moo", "dog": "woof"}
    
#Better way to do this??
class ExampleSubClass():
    def __init__(self):
        super().map1.update({"c": 3})
        super().map2.update({"duck": "quack"})

Aucun commentaire:

Enregistrer un commentaire