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

肥鼠路易發表於2020-11-24

原始碼

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_

相關文章