我正在构建一个继承自另一个类Parent的类Child. Parent类有一个Child将使用的loadPage方法,除了Child需要在loadPage函数末尾附近但在函数的最终语句之前运行自己的代码.我需要以某种方式将此函数仅插入到load的实例中,而不是父实例.我正在考虑将一个customFunc参数放入loadPage并将其默认设置为None for Parent,但默认为someFunction for Child.
如何仅为Child的实例更改loadPage方法的默认值?或者我错了吗?我觉得我可能会忽略一个更好的解决方案.
class Parent():
def __init__(self):
# statement...
# statement...
def loadPage(self, pageTitle, customFunc=None):
# statement...
# statement...
# statement...
if customFunc:
customFunc()
# statement...
# statement...
class Child(Parent):
def __init__(self):
Parent.__init__(self)
self.loadPage.func_defaults = (self.someFunction) #
解决方法:
对于这样的事情,我以不同的方式做到:
class Parent():
def loadPage(self, pageTitle):
# do stuff
self.customFunc()
# do other stuff
def customFunc(self):
pass
class Child(Parent):
def customFunc(self):
# do the child stuff
然后,一个Child实例将在customFunc中执行这些操作,而Parent实例将执行“标准”操作.
标签:python,defaults,template-method-pattern