Родительский класс, который я пишу, требует определенной внутренней очистки после использования. Дочерний класс имеет свою собственную очистку, но функция очистки родителя должна быть запущена позже. Очевидно, что вызов super решил бы это, но я бы хотел, чтобы это было как можно проще на стороне дочернего класса.
Я попытался украсить родительский метод. Это не сработало.
# The parent class whose inner-workings I don't expect the end user to understand
class ParentClass(object):
def __init__(self, *args, **kwargs):
self._personal_message = "Parent class says:"
self._important_message = "I'm important!"
# The method that NEEDS to be run in all instances of ParentClass and its subclasses
def _important_method(self):
print(self._important_message)
# The decorator I thought would work
def _pretty_decoration(func):
def func_wrapper(self):
func_self = func(self)
self._important_method()
return func_self
return func_wrapper
# The decorated function that will be overridden by the child class
@_pretty_decoration
def do_something(self):
print(self._personal_message)
# Make the decorator static
_pretty_decoration = staticmethod(_pretty_decoration)
# The blissfully naive Child class
class ChildClass(ParentClass):
def __init__(self, *args, **kwargs):
super(ChildClass, self).__init__(*args, **kwargs)
self._personal_message = "Child class says:"
# The overriding method
def do_something(self):
print(self._personal_message)
self.do_something_else()
def do_something_else(self):
print("I am blissfully naive.")
# The test drive
parent = ParentClass()
parent.do_something()
child = ChildClass()
child.do_something()
В этом примере я получаю:
Parent class says:
I'm important!
Child class says:
I am blissfully naive.
тогда как я надеялся получить:
Parent class says:
I'm important!
Child class says:
I am blissfully naive.
I'm important!
Что я должен делать для ожидаемого результата?