TypeError: __init__() takes 2 positional arguments but 4 were given

TypeError: __init__() takes 2 positional arguments but 4 were given

我的代码给出的错误是 TypeError: __init__() takes 2 positional arguments but 4 were given。试图寻找一个额外的参数,但找不到。

尝试过以前回答的问题,但没有得到任何合适的解决方案。

我的代码如下:

from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
    def __init__(self,title,author):
        self.title=title
        self.author=author   
    @abstractmethod
    def display(): pass

#Write MyBook class
class MyBook(Book):
    def __init__(self, price):
        self.price = price

    def display():
        print('Title: {}'.format(title))
        print('Author: {}'.format(author))
        print('Price: {}'.format(price))

title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()

编译器报错如下

Traceback (most recent call last):
  File "Solution.py", line 23, in <module>
    new_novel=MyBook(title,author,price)
TypeError: __init__() takes 2 positional arguments but 4 were given

Python不会自动调用父class的init。您需要明确地执行此操作。

from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
    def __init__(self,title,author):
        self.title=title
        self.author=author   
    @abstractmethod
    def display(): pass

#Write MyBook class
class MyBook(Book):
    def __init__(self, price, title, author):
        super(MyBook, self).__init__(title, author)
        self.price = price

    def display():
        print('Title: {}'.format(title))
        print('Author: {}'.format(author))
        print('Price: {}'.format(price))

代码内的注释。

from abc import ABCMeta, abstractmethod


class Book(object, metaclass=ABCMeta): # 1. Why do you need meta class?
    def __init__(self, title, author):
        self.title=title
        self.author=author
    @abstractmethod
    def display(self): pass  # 2. Consider replacing with  raise NotImplementedError + missing 'self'


class MyBook(Book):
    def __init__(self, price, title, author):  # 3 You are missing two arguments in here.... (title and author)
        super(MyBook, self).__init__(title, author)  # 4 This line is missing
        self.price = price

    def display(self):
        print('Title: {}'.format(self.title))  # self missing in all three lines
        print('Author: {}'.format(self.author))
        print('Price: {}'.format(self.price))

title=input()
author=input()
price=int(input())
new_novel = MyBook(title, author, price)
new_novel.display()