我们说我们有以下课程:
class Base(object):
def load(self):
# do logic A
# do logic B
class Child(Base):
def load(self):
# do logic C
我知道装饰器可以用来扩展Python中的函数行为,但我不知道如何在我的情况下应用它。
调用Child's
load()
时,如何按此顺序执行以下代码?:
logic A
logic C
logic B
我不想要做什么
class Base(object)
def logicA()
pass
def logicB()
pass
def load()
pass
class Child(Base):
def load(self):
super.logicA()
# do logic C
super.logicB()
我只想编写逻辑C,而不必显式调用逻辑A和B
答案 0 :(得分:12)
你的意思是这样的:
class Base(object):
def load(self):
print('do logic A')
print('do logic B')
class Child(Base):
def load(self):
super().load()
print('do logic C')
c = Child()
c.load()
这将打印:
do logic A
do logic B
do logic C
我能想到的唯一另一种方式就是这个:
class Base(object):
def load(self):
print('do logic A')
self.new_logic() # call new logic from child class, if exist.
print('do logic B')
def new_logic(self):
# overwrite this one in child class
pass
class Child(Base):
def new_logic(self):
print('do logic C')
c = Child()
c.load()
打印:
do logic A
do logic C
do logic B