mdo*_*ong 1 python oop python-2.7
所以我有一个父类:
class Parent(Object):
def function(self):
do_something()
Run Code Online (Sandbox Code Playgroud)
许多儿童班:
class Child1(Parent):
def function(self):
do_something_else_1()
class Child2(Parent):
def function(self):
do_something_else_2()
...
Run Code Online (Sandbox Code Playgroud)
我想确保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()
...
Run Code Online (Sandbox Code Playgroud)
但我宁愿不为每个子类做这个,因为这些子类是动态生成的,因为这些子类本身正在进一步扩展.相反,我想做一些看起来像的事情
class Child1(Parent):
@call_parent
def function(self):
do_something_else_1()
class Child2(Parent):
@call_parent
def function(self):
do_something_else_2()
...
Run Code Online (Sandbox Code Playgroud)
并写一个装饰器来完成同样的任务.
我有两个问题:
这甚至是个好主意吗?我是否按照预期的方式使用装饰器和功能覆盖?
在不知道有关系统的详细信息的情况下,这个问题很难回答.仅从抽象示例看起来它看起来不错,但用super()类似的东西替换显式和清晰的调用@call_parent并不是一个好主意.
每个人都知道或者很容易找到什么super(),装饰者只会造成混乱.
我怎么去写这个装饰师?
不要写装饰器,而是可以使用模板方法:
class Parent(Object):
def function(self):
do_something()
do_something_in_child()
def do_something_in_child():
pass
Run Code Online (Sandbox Code Playgroud)
现在在子类中,您只能覆盖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
Run Code Online (Sandbox Code Playgroud)