Python ... takes 0 positional arguments but 1 was given

最近,博主在学习python时遇到这么个报错,

系统:windows10

开发环境:VS Code

Python版本:3.12

错误重现:

class Dog:
    def __init__(self):
        pass

    def 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 eatSomething
    self.eatBone()
TypeError: Dog.eatBone() takes 0 positional arguments but 1 was given

意思就是说,eatBone()这个方法没有参数,但在调用该方法时传递了一个参数。

可博主明明没有传递参数呀!

查看官网解释:

Python3.12文档官网连接

意思是说,类中的函数在被调用时,会自动多一个self的参数,就是类本身。因此,在类中的函数定义时要显式地加一个self参数。

如eatSomething(self)方法。

修改程序:

class Dog:
    def __init__(self):
        pass

    def 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...

结束!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值