python - TypeError: __init__() 接受 2 个位置参数,但给出了 4 个
问题描述
我的代码给出的错误为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
解决方案
代码内的注释。
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()
推荐阅读
- wordpress - Wordpress - “关闭”类已在页面加载时添加到“acf-field-group-fields”
- php - PHPmailer 邮件正文中不必要的空间
- javascript - TypeError:无法读取未定义的属性“布尔”
- python - Django REST 单元测试 TypeError: __init__() 接受 1 个位置参数,但给出了 2 个
- linux - 根据 SSH 主机或身份指定 Git 身份
- javascript - 如何生成从 java servlet 到 HTML 页面的警报框?
- python - python - 更改png文件中单词的颜色(搜索单词并更改单词的颜色)
- jenkins - 如何将 SonarQube 与 QuickBuild 集成?
- react-native - TypeError:未定义不是函数(评估'store.getState()')
- php - 雄辩的关系和类与构造函数