一个关于类的问题,哪位能帮帮忙
有一个书店类,一个书类,要求书店类具有计算书籍总价,查找书籍的功能
class Bookstore:
sum_price = 0
book_index = 0
def __init__(self):
self.books = []
self.books_price=[]
def add_book(self, title, author, price):
self.books.append(Book(title, author, price))
def total_price(self):
return self.sum_price
def find_book(self, book_name):
for obj in self.books:
if obj.title == book_name:
return obj.__str__()
else:
return "The book could not be found in the book store."
class Book(Bookstore):
def __init__(self,title,author,price):
super().__init__()
self.title=title
self.author=author
self.price=price
Bookstore.book_index += 1
Bookstore.sum_price += self.price
def write(self):
print(self.title, self.author, self.price)
def __str__(self):
return f'title:{self.title}\n' \
f'author:{self.author}\n' \
f'price:{self.price}'
bs=Bookstore()
b1=Book("高数","清华",20)
b2=Book("现代","清华",23)
total_price=bs.total_price()
print(total_price)
print(Bookstore.find_book("高数"))
报错 TypeError: find_book() missing 1 required positional argument: 'book_name' 怎么解决
在调用 Bookstore.find_book() 方法时需要传入一个参数 book_name,但是在代码中没有传入该参数,导致报错。可以修改代码,在调用 Bookstore.find_book() 方法时传入需要查找的书名,例如:
total_price=bs.total_price()
print(total_price)
print(bs.find_book("高数"))
这样就能正确调用 Bookstore.find_book() 方法,查找书籍信息并输出了。另外需要注意的是,在 Bookstore.find_book() 方法中,查找到书籍后应该直接返回对应书籍的信息,而不是在第一个未匹配到书名的书籍上返回 "The book could not be found in the book store."。修改后的 Bookstore.find_book() 方法如下:
def find_book(self, book_name):
for obj in self.books:
if obj.title == book_name:
return obj.__str__()
return "The book could not be found in the book store."
```python
这样修改后,当没有找到对应书名的书籍时才会返回 "The book could not be found in the book store."。
```
出现这个错误是因为在调用find_book()函数时,没有传入book_name参数,解决方法是在调用find_book()函数时传入book_name参数,例如:
print(Bookstore.find_book("高数")) # 传入book_name参数