Python错误集锦:调用类方法时提示TypeError: prt() takes 0 positional arguments but 1 was given

原文链接:http://www.juzicode.com/archives/3823

错误提示:

调用自定义class的方法时提示:TypeError: prt() takes 0 positional arguments but 1 was given

#juzicode.com/vx:桔子code  
class Fruit:
    def __init__(self,name):
        self.name = name
    def prt():
        print(self.name)
    
f = Fruit('桔子')
f.prt()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-7fa38293fe49> in <module>
      7 
      8 f = Fruit('桔子')
----> 9 f.prt()

TypeError: prt() takes 0 positional arguments but 1 was given

错误原因:

1、Fruit的prt()方法原意是不带任何入参,使用print()函数打印自己的name属性,因为prt方法在调用的时候默认使用了self入参,所以提示:but 1 was given。

解决方法:

1、在prt()方法中传入self入参:def prt(self)

#juzicode.com/vx:桔子code  
class Fruit:
    def __init__(self,name):
        self.name = name
    def prt(self):
        print(self.name)
    
f = Fruit('桔子')
f.prt()

扩展内容:

  1. Python基础教程7–类(class)


关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注