所以我有一个父类:
class Parent(Object):
def function(self):
do_something()
还有很多子类:
class Child1(Parent):
def function(self):
do_something_else_1()
class Child2(Parent):
def function(self):
do_something_else_2()
...
我想确保父级 function() 总是在子级 function() 之前被调用,这样每次调用 function() 也调用 do_something() 无论类。现在,我知道我可以做类似的事情:
class Child1(Parent):
def function(self):
super(Child1, self).function()
do_something_else_1()
class Child2(Parent):
def function(self):
super(Child2, self).function()
do_something_else_2()
...
但我不想为每个子类都这样做,因为这些子类是动态生成的,并且因为这些子类本身正在进一步扩展。相反,我想做一些看起来像的事情
class Child1(Parent):
@call_parent
def function(self):
do_something_else_1()
class Child2(Parent):
@call_parent
def function(self):
do_something_else_2()
...
并编写一个装饰器来完成同样的任务。
我有两个问题:
- 这是个好主意吗?我是否以预期的方式使用装饰器和功能覆盖?
- 我将如何编写这个装饰器?
请您参考如下方法:
Is this even a good idea? Am I using decorators and function overriding in their intended way?
如果不了解您系统的详细信息,这个问题很难回答。 仅从抽象示例来看它看起来不错,但是用 @call_parent 之类的东西替换显式和清晰的 super() 调用并不是一个好主意。
每个人都知道或很容易找出 super() 的作用,装饰器只会造成混淆。
How would I go about writing this decorator?
不要写装饰器,相反你可以使用 template method :
class Parent(Object):
def function(self):
do_something()
do_something_in_child()
def do_something_in_child():
pass
现在在子类中你只需要覆盖do_something_in_child,function只保留在Parent中,所以你确定你的 do_something() 总是被调用。
class Child1(Parent):
def do_something_in_child(self):
do_something_else_1():
class Child2(Parent):
def do_something_in_child(self):
do_something_else_2():
class Child3(Parent):
# no override here, function() will do the same what it does in Parent
pass
