我正在构建一个类 Child,它继承自另一个类 Parent。 Parent 类有一个 Child 将使用的 loadPage 方法,除了 Child 需要在接近 loadPage 函数末尾但在该函数的最终语句之前运行自己的代码。我需要以某种方式将此函数插入到 loadPage 中,仅用于 Child 的实例,而不是 Parent。我正在考虑将 customFunc 参数放入 loadPage 并将其默认为 Parent 的 None,但将其默认为 someFunction 的 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) #<-- This doesn't work
最佳答案
对于这样的事情,我用不同的方式来做:
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 - 如何更改 Python 中的方法默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7100054/