Python成功解决TypeError: __init__() missing 1 required positional argument: ‘comment‘

源代码

class Book:
 
    def __init__(self, name, author, comment, state = 0):
        self.name = name
        self.author = author
        self.comment = comment
        self.state = state
 
# 创建一个Book类的子类 FictionBook
class FictionBook(Book):
    def __init__(self,name,author,comment,state = 0,type_='虚构类'):
    # 继承并定制父类的初始化方法,增加默认参数 type = '虚构类',让程序能够顺利执行。
        Book.__init__(name,author,comment,state = 0)
        self.type=type_
    def __str__(self):
        status = '未借出'
        if self.state == 1:
            status = '已借出'
        return '类型:%s 名称:《%s》 作者:%s 推荐语:%s\n状态:%s ' % (self.type, self.name, self.author, self.comment, status)


book = FictionBook('囚鸟','冯内古特','我们都是受困于时代的囚鸟')
print(book)

报错类型

line 13, in __init__
    Book.__init__(name,author,comment,state = 0)
TypeError: __init__() missing 1 required positional argument: 'comment'

解决方法

Book.__init__里面加上self

Book.__init__(self,name,author,comment,state = 0)
        self.type=type_

self代表实例化对象本身
①、类的方法内部调用其他方法时,我们也需要用到 self 来代表实例
②、类中用 def 创建方法时,就必须把第一个参数位置留给 self,并在调用方法时忽略它(不用给self传参)
③、类的方法内部想调用类属性或其他方法时,就要采用 self.属性名 或 self.方法名 的格式

不定长参数

def a(*cc,dd=1,ee=2,ff=3,gg=4):
    print(cc)
    
a(5,6,7,8,9)
# 结果是 5,6,7,8,9

不定长参数是不确定个数的,只要不写参数名,全都默认是不定长参数。

猜你喜欢

转载自blog.csdn.net/weixin_44991673/article/details/110099428
今日推荐