问题描述
当我们在使用 Python 中的 super() 函数时,有时候会遇到报错信息TypeError: 'super' object is not callable 。这个报错信息告诉我们,无法调用 super() 函数,可能会让我们困惑和不知所措。下面,我们就来详细讲解一下这个问题的原因及解决方法。
原因分析
super() 是 Python 中一个很常用的函数,它常常用于在子类中调用父类的方法。而在出现 TypeError: 'super' object is not callable 的时候,通常是因为我们在使用 super() 函数时出现了一些问题。
举个例子,比如我们有一个父类 Shape ,其中有一个 draw() 方法:
class Shape:
def draw(self):
print("Drawing a shape.")
现在我们想创建一个子类 Circle ,它继承自 Shape ,并且覆盖了 draw() 方法,用于绘制圆形:
class Circle(Shape):
def draw(self):
print("Drawing a circle.")
如果我们想在 Circle 类中调用 Shape 类的 draw() 方法,我们可以使用 super() 函数,并将当前类和实例对象作为参数传递给它:
class Circle(Shape):
def draw(self):
super(Circle, self).draw()
print("Drawing a circle.")
但是,如果我们不小心将 super() 写成了 super ,就会出现 TypeError: 'super' object is not callable 的错误。因为在 Python3 中,super 是一个类,不是一个函数。因此应该写成 super().init() ,或者使用 super().draw() 来调用父类的方法。
解决方法
正如上面所述,错误主要是由于 super() 的写法不正确造成的。为了避免这种错误,我们需要始终将 super() 写成函数调用,并将当前类和实例对象作为参数传递给它。具体来说,我们可以使用以下三种方法来解决这个问题:
1.将 super() 写成函数调用:
class Circle(Shape):
def draw(self):
super().draw()
print("Drawing a circle.")
2.将类名写成硬编码,这种方式不太优雅,但也可以解决这个问题:
class Circle(Shape):
def draw(self):
super(Circle, self).draw()
print("Drawing a circle.")
3.使用多重继承时,我们必须将父类的名称写在 super() 的参数中:
class Shape:
def draw(self):
print("Drawing a shape.")
class Fill:
def color(self):
print("Filling with color.")
class Circle(Shape, Fill):
def draw(self):
super(Shape, self).draw()
print("Drawing a circle.")
super(Fill, self).color()
总结
在 Python 中,当出现 TypeError: 'super' object is not callable 错误时,通常是因为我们使用了不正确的 super() 语法。为了避免这个问题,我们需要始终将 super() 写成函数调用,并将当前类和实例对象作为参数传递给它。如果这个错误还是出现了,我们可以使用上面提到的三种方法来解决它。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python报”TypeError: ‘super’ object is not callable “的原因以及解决办法 - Python技术站