My code is giving the error as TypeError: __init__() takes 2 positional arguments but 4 were given
. tried searching for an extra argument but couldn’t get one.
Tried previously answered questions but didn’t get any proper solution.
My code is as follows:
JavaScript
x
24
24
1
from abc import ABCMeta, abstractmethod
2
class Book(object, metaclass=ABCMeta):
3
def __init__(self,title,author):
4
self.title=title
5
self.author=author
6
@abstractmethod
7
def display(): pass
8
9
#Write MyBook class
10
class MyBook(Book):
11
def __init__(self, price):
12
self.price = price
13
14
def display():
15
print('Title: {}'.format(title))
16
print('Author: {}'.format(author))
17
print('Price: {}'.format(price))
18
19
title=input()
20
author=input()
21
price=int(input())
22
new_novel=MyBook(title,author,price)
23
new_novel.display()
24
compiler gives runtime error as follows
JavaScript
1
5
1
Traceback (most recent call last):
2
File "Solution.py", line 23, in <module>
3
new_novel=MyBook(title,author,price)
4
TypeError: __init__() takes 2 positional arguments but 4 were given
5
Advertisement
Answer
Comments inside the code.
JavaScript
1
27
27
1
from abc import ABCMeta, abstractmethod
2
3
4
class Book(object, metaclass=ABCMeta): # 1. Why do you need meta class?
5
def __init__(self, title, author):
6
self.title=title
7
self.author=author
8
@abstractmethod
9
def display(self): pass # 2. Consider replacing with raise NotImplementedError + missing 'self'
10
11
12
class MyBook(Book):
13
def __init__(self, price, title, author): # 3 You are missing two arguments in here.... (title and author)
14
super(MyBook, self).__init__(title, author) # 4 This line is missing
15
self.price = price
16
17
def display(self):
18
print('Title: {}'.format(self.title)) # self missing in all three lines
19
print('Author: {}'.format(self.author))
20
print('Price: {}'.format(self.price))
21
22
title=input()
23
author=input()
24
price=int(input())
25
new_novel = MyBook(title, author, price)
26
new_novel.display()
27