dimanche 17 juillet 2022

What is the name of this design pattern with "cascading attributes"?

Say I have the following classes:

DO_NOT_OVERRIDE = type() # this dictates if an attribute won't be overridden.

class Parent():
    def __init__(self, a: int = 0, b: int = 0):
        self.a = a
        self.b = b

class Child():
    def __init__(self, parent: Parent, a: int = DO_NOT_OVERRIDE, b: int = DO_NOT_OVERRIDE):
        self.parent = parent
        
        self._a = a
        self._b = b

    @property
    def a(self):
        if self._a is DO_NOT_OVERRIDE:
            return self.parent.a

        return self._a

    @a.setter
    def a(self, value: int):
        self._a = value


    @property
    def b(self):
        if self._b is DO_NOT_OVERRIDE:
            return self.parent.b

        return self._b

    @b.setter
    def b(self, value: int):
        self._b = value

Now, let's create some objects.

parent_obj = Parent(a = 1, b = 2)
child_obj_1 = Child(parent = parent_obj)

child_obj_1.a would return 1 and child_obj_1.b would return 2, which are both values from parent.a and parent.b respectively

But consider another Child:

child_obj_2 = Child(parent_obj, a = 20)

child_obj_2.a would return 20 which is a value set in child_obj_2, though child_obj_2.bwould still return2sinceb` is not "overridden" by the child object.


What is this design pattern?

Aucun commentaire:

Enregistrer un commentaire