I was just starting to learn @property to implement getter and setter method in Python. I know that for it not to end up as a RecursionError, we have to change the attribute name locally, like putting an underscore as a prefix. But when I try to implement it, I got an AttributeError that says the object (a subclass) missing the particular attribute that I changed, as I mentioned earlier, in its superclass. Here is my code.
class Handler(ABC):
@property
def parent(self) -> Handler:
return self._parent
@parent.setter
def parent(self, parent: Handler):
self._parent = parent
@abstractmethod
def handle(self):
pass
def add_child(self, child):
pass
class ThingHandler(Handler):
def __init__(self, name):
self.name = name
self.string = self._make_string()
self._children: List[Handler] = list()
def handle(self):
... # method implementation, not important atm.
def add_child(self, child: Handler):
self._children.append(child)
child.parent = self
def __str__(self):
return self.string
def _make_string(self):
name = self.name.lower().replace(" ", "_")
return str(self.parent) + f".{name}"
I was just trying to initialize the ThingHandler
when I got an error in the _make_string
method specifically in the last line where I call self.parent. The error message is
AttributeError: 'ThingHandler' object has no attribute '_parent'. Did you mean: 'parent'?
referring to the return self._parent
line in Handler. I was also experimenting with python’s ABC in case it has something to do with the error.
Any solution/suggestion?