最近,博主在学习python时遇到这么个报错,
系统:windows10
开发环境:VS Code
Python版本:3.12
错误重现:
class Dog:def __init__(self):passdef eatSomething(self):self.eatBone()def eatBone():print("eat bone...")def eatMeat():print("eat meat...")dog = Dog()
dog.eatSomething()
报错:
Traceback (most recent call last):File "e:\ProjectWorkSpace\PythonProgram\PythonCodeInVsCode\python_work\Chapter15\test.py", line 15, in <module>dog.eatSomething()File "e:\ProjectWorkSpace\PythonProgram\PythonCodeInVsCode\python_work\Chapter15\test.py", line 6, in eatSomethingself.eatBone()
TypeError: Dog.eatBone() takes 0 positional arguments but 1 was given
意思就是说,eatBone()这个方法没有参数,但在调用该方法时传递了一个参数。
可博主明明没有传递参数呀!
查看官网解释:
Python3.12文档官网连接
意思是说,类中的函数在被调用时,会自动多一个self的参数,就是类本身。因此,在类中的函数定义时要显式地加一个self参数。
如eatSomething(self)方法。
修改程序:
class Dog:def __init__(self):passdef eatSomething(self):self.eatBone()def eatBone(self):print("eat bone...")def eatMeat(self):print("eat meat...")dog = Dog()
dog.eatSomething()
dog.eatMeat()
结果:
eat bone...
eat meat...
结束!