[英]TypeError: __init__() takes from 1 to 3 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
代碼中的注釋。
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()
Python 不會自動調用父類的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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.