我想覆盖Python中dict
类的一个方法,一个简单的方法:update
。假设我想创建一个与标准 dict
相同的 MyDict
类,除了它可以用必须包含在至少 10 个元素。
所以我会这样继续:
def update(self, newdict):
if len(newdict) <= 10: raise Exception
self.update(newdict)
但在 update
的内部调用中,显然 Python 调用了重写函数而不是原始函数。除了简单地更改函数名称之外,是否有其他方法可以避免这种情况?
最佳答案
您需要在父类(super class)上调用update
,提供子类的一个实例作为self
。
def update(self, newdict):
if len(newdict) <= 10: raise Exception
dict.update(self, newdict)
您还可以使用 super()
在运行时确定父类(super class):
def update(self, newdict):
if len(newdict) <= 10: raise Exception
super(MyDict, self).update(newdict)
在 Python 3 中,您可以省略 super()
的参数:
def update(self, newdict):
if len(newdict) <= 10: raise Exception
super().update(newdict)
关于python - 覆盖方法而不陷入无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199436/