0

I have an example below where I reference self.attrs in self.properties in the base class. If I child class updates self.attrs like in the case of Child1, id like it to be that value when i unpack self.properties. If i do not change it, id like it to be whatever it was in the parent class. See below.

class Parent():
    def __init__(self):
        self.attrs = {}

        self.properties = {
            "attrs": self.attrs,
            "method": self.parentMethod(),
        }

    def parentMethod(self):
        return "Parent Method"

class Child1(Parent):
    def __init__(self):
        super().__init__()
        self.attrs = {"name": "Bob"}

        self.properties = {
            **self.properties,
            "method": self.childMethod(),
        }

    def childMethod(self):
        return "Child1 Method"

class Child2(Parent):
    def __init__(self):
        super().__init__()

        self.properties = {
            **self.properties,
            "method": self.childMethod(),
        }

    def childMethod(self):
        return "Child2 Method"
Sal Aslam
  • 9
  • 1

1 Answers1

0

If you want a method that looks like an instance variable, then you want a property.

class Parent():
    def __init__(self):
        self.attrs = {}

    @property
    def properties(self):
        return {
            "attrs": self.attrs,
            "method": self.parentMethod(),
        }

    def parentMethod(self):
        return "Parent Method"

Then a new dictionary will be constructed when self.properties is accessed, and it will always use the current value of self.attrs. Note that, with this approach, you don't want to set self.properties again in the child class; it will always reflect the current status of the class whenever referenced.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116