PHP前端开发

Python 实例化对象出错:调用参数与定义参数个数不符的原因是什么?

百变鹏仔 2个月前 (01-14) #Python
文章标签 参数

python 实例化对象出错:调用参数与定义参数个数不符

在 python 中定义类并实例化对象时,经常会遇到参数传递与定义不符的错误。本文针对一个具体示例,探讨其原因和解决方法。

代码示例

class people():    def __init__(self, height, money):        self.height = height        self.money = moneyclass man(people):    def __init__(self, age):        self.age = ageman(11, 22)

运行这段代码会产生以下错误:

立即学习“Python免费学习笔记(深入)”;

typeerror: __init__() takes 2 positional arguments but 3 were given

问题原因

错误提示指出,man 类的 __init__ 函数定义了接收两个参数,但实例化时传递了三个参数。之所以会出现这种情况,是因为我们在调用子类 man 的 __init__ 函数时, помимо 11 和 22 两个显式传递的参数外,实例本身 (self) 也算作一个参数。

解决方法

解决方法是确保在实例化时传递的参数个数与类定义的 __init__ 函数的参数个数一致。在这个示例中,我们可以将 __init__ 函数中的参数个数从两个修改为三个,如下所示:

class Man(People):    def __init__(self, age, height, money):        self.age = age        self.height = height        self.money = moneyMan(11, 22, 3000)

通过这种修改,实例化代码的传递参数个数与类定义的 __init__ 函数的参数个数一致,因此可以成功实例化 man 对象。