我正在尝试通过使用book类和bookstore类使用python模拟书店。我如何关联这两个类以及如何制作,以便将图书类自动添加到用于操纵图书的BookStore类中
class Book(object):
def __init__(self, ID, title, ISBN, authorsList, edition,
publication_date, no_of_pages, purchase_price,
selling_price, quantity, discount):
try:
self.ID = int(ID)
self.title = str(title)
self.ISBN = str(ISBN)
self.authorsList = str(authorsList)
self.edition = str(edition)
self.publication_date = str(publication_date)
self.no_of_pages = int(no_of_pages)
self.purchase_price = float(purchase_price)
self.selling_price = float(selling_price)
self.quantity = int(quantity)
self.discount = float(discount)
except:
print("Error has occurred!")
def getID(self):
try:
return self.ID
except:
print("Error has occurred!")
def setID(self, ID):
try:
self.ID = ID
except:
print("Error has occurred!")
def gettitle(self):
try:
return self.title
except:
print("Error has occurred!")
def __str__(self):
return "Book ID: {}\n Book Title: {}\n Book ISBN: {}\n Book Authors List: {}\n Book Edition: {}\n Book Publication Date: {}\n Book Number of pages: {}\n Book Purchase Price: {}\n Book Selling Price: {}\n Book Quantity: {}\n Book Discount: {}".format(self.ID, self.title, self.ISBN, self.authorsList, self.edition, self.publication_date, self.no_of_pages, self.purchase_price, self.selling_price, self.quantity, self.discount)
class BookStore(Book):
def __init__(self):
self.itemlist =[]
def addBook(self, Book):
return self.itemlist.append(Book)
def DisplayBook():
for i in self.itemlist:
print(i.__str__())
def SearchBookID():
self.itemlist = []
for Book in self.ID:
if Book.ID == ID:
ID.append(Book)
return ID
def delBookID():
return self.itemlist.remove(Book)
答案 0 :(得分:0)
如果您确实要-尽管不建议这样做-您可以创建类似class variable
的内容
>>> class BookStore:
booklist = []
>>> BookStore.booklist.append(1)
>>> BookStore.booklist.append(2)
>>> BookStore.booklist
[1, 2]
现在在您的__init__
类的Book
方法中添加BookStore.booklist.append(book)