Classes Error Indentation? But where? - python
this is my product class
class Product(object):
def __init__(self,price,name,catalognum,starRating):
self.price = price
self.name = name
self.catalognum = catalognum
self.starRating = starRating
def __str__():
print "Catalognum:[0]\n\
Name: [1]\n\
Price: $[2]\n\
Rating: [3]".format(catalognum,name,price,num_starRating)
def num_starRating(self):
return "*"*int(self.rating)
class Book(object):
def __init__(self,price,name,catalognum,starRating,author,ISBN,publisher):
self.price = price
self.name = name
self.catalognum = catalognum
self.starRating = starRating
self.author = author
self.ISBN = ISBN
self.publisher = publisher
def __str__():
print "author:[0]\n\
Title:[1]\n\
Price:$[2]\n\
ISBN:[3]\n\
Publisher:[4]\n\
Rating[5]".format(author,Title,Price,ISBN,num_starRating)
class Movie(object):
def __init__(self,Director,Studio,Title,Price,Running_Time,starRating,name,catalognum):
self.Director = Director
self.Studio = Studio
self.Title = Title
self.Price = Price
self.Running_Time = Running_Time
self.starRating = starRating
self.name = name
self.catalognum = catalognum
def __str__():
print "Director:[0]\n\
Title:[1]\n\
Price:[2]\n\
Running_Time:[3]min\n\
Studio:[4]\n\
Rating[5]".format(Director,Title,Price,Running_Time,Studio,num_starRating)
This is my catalog class
class Catalog(object):
def __init__(self,product_file):
self.product_file = product_file
sortByColumn = 0
self.cataloglist = self.BuildCatalogList
def BuildCatalogList(self):
file = open(self.product_file,"r")
filelist = file.readlines()
product_list = []
for i in range(1,len(file_list)):
product = filelist[i].split(',')
item = product(float(product[2]),int(product[3]),product[1],product[0])
product_list.append(item)
return product_list
def setsortby(self,sortype):
self.sortbycolumn = sorttype
def printcatalogtable(self):
print “[0][1][2][3]”.format(“catalog #”,”name”,”price($)”,”rating”)
import os
directory = os.listdir(“.”)
for filename in directory:
if filename [:-3:] == “pyc”:
os.remove(filename)
catalog = catalog(“bookdata.txt)
for printcatalogtable
print”[0:20]][1:25][2:15][3]”.format(“catalog #”,”name”,”price($)”,”rating)
for product in cataloglist:
print “(0:20)(1:25)(2:15.2f) (3)”[3]”.format(product,catalognum,product,name,price,name,product,price,product.getstarrating())
Using two classes, I tried to print out my file i have saved in format that follows catalog class
but its not working out, any ideas?
It should work out like this:
Catalog Number (6 digits),Title,Price,Star Rating (1-5),Author First Name,Author Last Name,ISBN,Publisher
123456,Game of Thrones: A Song of Ice and Fire,11.99,5,George RR,Martin,9780553582017,Random House Publishing Group
654321,City of Bones,11.99,4,Cassandra,Clare,9781406331400,Margaret K McElderry Books
654613,How I Met My Husband,14.99,4,Alice,Munro,2354365435123,Book Bublishers Inc
524638,The Hunger Games,9.99,4,Susan,Collins,9780439023481,Scholastic Press
632356,Lives of the Saints,19.99,2,Ninno,Ricci,8883336666,Harol Hitch Hijackers Books
675031,1984,11.99,5,George,Orwell,1782127755,Secker and Warburg London
111111,Forbidden City,5.99,1,William,Bell,4435-13422453,Lamest Books Corp
315644,Harry Potter and the Prisoner of Azkaban,14.99,5,JK,Rowling,64569-7861-0537,Raincoast
478931,Fifty Shades of Grey,2.99,0,EL,James,783844-6512-982,BooksBooksBooks Inc.
101010,Breaking Dawn,0.99,1,Stephanie,Meyer,101010-1010-101,LOLOLOLOL Press
548573,The Great Gatsby,14.99,4,F Scott,Fitzgerald,9781597226769,Scribners
123827,Steve Jobs,39.99,4.5,Walter,Isaacson,9781451648539,Google Inc
453123,Twilight,0.1,1,Stephenie,Meyer,9781594133299,Simons Inc.
445234,A Midsummer Night's Dream,10.99,3,William,Shakespeare,123455-4322-144,Penguin Group
542324,Paper Town,12.99,2,John,Green,698773-3122-341,Penguin Group
991337,Shutter Island,19.99,4.5,Dennis,Lehane,1234567890154,Awesome Group
123431,The Magic School Bus at the Waterworks,50,5,Joanna ,Cole,0-590-40360-5,Scholastic Corporation
Your BuildCatalogList starts at 0 spaces this should be changed as below (and of course for all the other functions that belong to the class Catalog.
class Catalog(object):
def __init__(self,product_file):
self.product_file = product_file
sortByColumn = 0
self.cataloglist = self.BuildCatalogList
# Spaces added to this function.
def BuildCatalogList(self):
file = open(self.product_file,"r")
filelist = file.readlines()
product_list = []
for i in range(1,len(file_list)):
product = filelist[i].split(',')
item = product(float(product[2]),int(product[3]),product[1],product[0])
product_list.append(item)
return product_list
The indentation of __init__ and __str__ methods of Book and Movie classes are wrong. Indent it properly.
Related
Functions aren't printing messages but program completely runs?
Hello I am currently working on updating a project from when I first was learning to code. With that being said I am starting to implement classes withing the program when I have run into a bit of a Issue not like a physical Python Error but my Class Functions just don't seem to perform properly. WebSite.py class WebSite: def __init__(self, url, id): self.__url = url self.__id = id def getURL(self): return self.__url def getId(self): return self.__id GunSite.py > class GunSite(WebSite): def __init__(self, url): self.__url = url self.__id = { 'shotgun' : 'shotguns', 'handgun' : 'handguns', 'rifle' : 'rifles', 'tactical' : 'tactical' } self.__lcount = 0 self.__gun_listings = [] super().__init__(self.__url, self.__id) def setKeyValue(self, key, value): self.__id[key] = value def getKeys(self): for id in self.__get(): print(id) def __get(self): for id in self.__id: yield self.__id[id] def getKey(self, key): return self.__id[key] def __addListing(self, listing): self.__gun_listings.append(listing) print(f"Added New Listing {self.__gun_listings(self.__lcount)} to Listings List") self.__lcount = self.__lcount + 1 def gatherListings(self, url): html_url = requests.get(url).text soup = BeautifulSoup(html_url, "lxml") listings = soup.find_all('div', class_='col-6 col-md-4 outer-tiles product-impression') for listing in listings: print("Gathering Listing name, price, etc..") name = listing.find('span', class_='first-line d-lg-none').text price = listing.find('span', class_='sales').text desc = listing.find('div', class_='pdp-link') desc_url = desc.a['href'] print("Gathered Listing Data!") print("Creating new GunListing Object...") gun_listing = GunListing(name, price, desc, desc_url) print("Object Created successfully!") print("Adding Listing Object to List of Listings...") self.__addListing(gun_listing) print("Finished Successfully! def getListings(self): print("Displaying Data for all Listings") for glisting in self.__gun_listings: name = glisting.getName() price = glisting.getPrice() desc = glisting.getDesc() desc_url = glisting.getDescURL() print(f"-----------------------------------------------------------") print(f"Listing Name: {name}") print(f"Listing Price: {price}") print(f"Desc: {desc}") print(f"For more info about this handgun, Visit {desc_url}") print(f"-----------------------------------------------------------") Listing.py class Listing: def __inti__(self, name, price, desc, desc_url): self.__name = name self.__price = price self.__desc = desc self.__desc_url = desc_url def getName(self): return self.__name def getPrice(self): return self.__price def getDesc(self): return self.__desc def getDescURL(self): return self.__desc_url GunListing.py from Listing import Listing class GunListing(Listing): def __init__(self, name, price, desc, desc_url): self.__name = name self.__price = price self.__desc = desc self.__desc_url = desc_url super().__init__(self.__name, self.__price, self.__desc, self.__desc_url) I expected the program to run through and complete everything in every function that I have created and called. But it isn't running anything in my functions just the code on the outside of the functions. CODE IM RUNNING gun_site = GunSite('https://www.cheaperthandirt.com/') print(f"Gathering Listings for Website {gun_site.getURL()}") gun_site.gatherListings(gun_site.getURL() + gun_site.getKey('shotgun') + '/') print(f"Finished Successfully Gathering Listings for {gun_site.getURL()}") print(f"Collecting All of the Listings from {gun_site.getURL()}") gun_site.getListings() print(f"Successfully Collected and Displayed Listings form {gun_site.getURL()}")
I am unsure why global variable won't update when accessed in class
Global variable will not update after I update the global variable within the function setProdID inside of the class Product. I add 1 to it, to make a new Product ID but it always stays at 0, then 1 gets added to it. prodIDCounter = 0 class NameType: def __init__(self, nameUse): self.nameUse = nameUse class Product: def __init__(self, prodName, price): self.prodName = prodName self.price = price def setProdName(self, newProdName): self.prodName = newProdName def setReview(self, review): self.review = review def setPrice(self, price): self.price = price #Whenever a new product is created, it gets a unique prodID, that increments by 1 each time def setProdID(): global prodIDCounter prodIDCounter += 1 return prodIDCounter review = "" prodID = setProdID() class Audio(Product): def __init__(self, prodName, price, NameType): self.prodName = prodName self.price = price self.singer = NameType.nameUse def setGenre(self, genre): self.genre = genre def printInfo(self): print("[Music]") print("Product ID: " + str(self.prodID) + " Product Name: " + self.prodName) print("Price: $" + str(self.price) + " Product Review Rate: " + str(self.review)) print("Singer Name: " + self.singer) print("Genre: " + self.genre + "\n") genre = "" class Cart: def __init__(self, NameType): self.owner = NameType.nameUse def addItem(self, Product): self.purchasedItems.append(Product.prodID) def removeItem(self, prodIDRemove): pass def displayCart(): pass MAX_ITEMS = 7 purchasedItems = [] #---------------------------------------------- #Create my cart here, Start of Main Test Driver name1 = NameType("Bailey") myCart = Cart(name1) print(myCart.owner) name1 = NameType("Music Artst") music1 = Audio("Song Name", 5.50, name1) music1.setReview(8.2) music1.setGenre("Pop") music1.printInfo() name1 = NameType("Music Artist 2") music2 = Audio("Song Name 2", 6, name1) music2.setReview(7) music2.setGenre("Punk") music2.printInfo() myCart.addItem(music1) myCart.addItem(music2) print(myCart.purchasedItems) My code read out is: Bailey [Music] Product ID: 1 Product Name: Song Name Price: $5.5 Product Review Rate: 8.2 Singer Name: Music Artst Genre: Pop [Music] Product ID: 1 Product Name: Song Name 2 Price: $6 Product Review Rate: 7 Singer Name: Music Artist 2 Genre: Punk [1, 1] I have tried multiple ways of doing it, but it never update the global variable and I am at a loss for what I should do. I keep geting the productID reading as 1 for all of the catalog entries. It adds the 1, but then forgets about it when prodIDCounter is called again when I make a new object.
Bookshelf classes getting title and genre of book
I'm trying to write a code that adds 'fiction' books to a Bookshelf and then prints the names of the 'fiction' books. This is what I have so far. class Book: def __init__(self,title,genre): self.title = title self.genre = genre def get_book(self): return self.title class Bookshelf: def __init__(self,title,genre,books): self.title = title self.genre = genre self.books = [] def add_book(self,book): self.books.append(books) return True s1 = Book('Black Roses', 'Fiction') s2 = Book('Red and Grey', 'Non-fiction') s3 = Book('Pride and Prejudice','Fiction') bookshelf = Bookshelf('Fiction') Any help?
class Book: def __init__(self,title,genre): self.title = title self.genre = genre def get_book(self): return self.title class Bookshelf: def __init__(self): self.books = [] def add_book(self,book): self.books.append(book) return True def get_book(self, genre): res = [] for book in self.books: if book.genre==genre: res.append(book.title) return res s1 = Book('Black Roses', 'Fiction') s2 = Book('Red and Grey', 'Non-fiction') s3 = Book('Pride and Prejudice','Fiction') z = Bookshelf() z.add_book(s1) z.add_book(s2) z.add_book(s3) z.get_book('Fiction') output ['Black Roses', 'Pride and Prejudice']
Since the Bookshelf.__init__ method initializes self.books to an empty list, there's no need for the books parameter. Since each bookshelf is devoted to a specific genre, you should make sure that books are not put on the wrong shelf. class Bookshelf: def __init__(self,title,genre): self.title = title self.genre = genre self.books = [] def add_book(self,book): if self.genre != book.genre: raise ValueError(r"Can't put a {book.genre} book on a {self.genre} shelf") self.books.append(books) s1 = Book('Black Roses', 'Fiction') s2 = Book('Red and Grey', 'Non-fiction') s3 = Book('Pride and Prejudice','Fiction') f = Bookshelf("Fiction Books", "Fiction") nf = Bookshelf("Non-Fiction Books", "Non-fiction") f.add_book(s1) nf.add_book(s2) f.add_book(s3) # Print all fiction books for book in f.books: print(book.get_book())
How do you add 2 inputs from an argument together?
I have made this code and now I want to add from the class 'Product' the price together. So I have 2 products: Computer and Nintendo and I want to add the price together, can I make a definition for this so that from product 3 and 4 it will also add up? I hope my question makes sense, I'm a beginner in programming. class Customer: def __init__(self, ID, name, address): self.ID = ID self.name = name self.address = address def customer_information(self): print('ID: '+ self.ID + ', Name: ' + self.name + ', Address: '+ self.address) class Product: def __init__(self, product_name, product_ID, price): self.product_name = product_name self.product_ID = product_ID self.price = price def product_information(self): print(self.product_name+', '+self.product_ID + ', €'+str(self.price)) class Order: def __init__(self): self.customer = [] self.product = [] def add1(self, product): self.product.append(product) def customer_data(self, customer): self.customer.append(customer) def show(self): for c in self.customer: c.customer_information() print('This order contains:') for p in self.product: p.product_information() customer1 = Customer('542541', 'Name', 'Rotterdam') customer2 = Customer('445412', 'Name', 'Schiedam') product1 = Product('Computer', '34456', 200.00) product2 = Product('Nintendo', '12345', 14.99) product3 = Product('Camera', '51254', 50.00) product4 = Product('Go-pro', '51251', 215.00) myOrder = Order() myOrder.customer_data(customer1) myOrder.add1(product1) myOrder.add1(product2) myOrder1 = Order() myOrder1.customer_data(customer2) myOrder1.add1(product3) myOrder1.add1(product4) myOrder.show() myOrder1.show()
Seems like you want to get the sum of all the product prices, or order totals. Both are the same result, but you have two classes that contain the same information so you can calculate the sums by either Product or Order: productsum = product1.price + product2.price + product3.price + product4.price ordersum = sum([p.price for p in myOrder.product]) + sum([p.price for p in myOrder1.product]) print(productsum) # 479.99 print(ordersum) # 479.99 Either way you'll get the same answer, just choose how you want to implement it.
Yes, you can create another variable in class order like- def __init__(self): self.customer = [] self.product = [] self.total = 0 and add every product's price to the total whenever a product is added to the list- def add1(self, product): self.product.append(product) self.total += product.price
TypeError: __init__() takes exactly 8 arguments (7 given) Python Homework
I can't figure out why I am getting the TypeError. Below is a class and two sub-classes. The first two work fine. The Final sub-class(OperatingSys) is where I am finding difficulty. I have put my Error input at the very bottom. Thanks in advance! class InventoryItem(object): def __init__(self, title, description, price, store_id): self.title = title self.description = description self.price = price self.store_id = store_id def __str__(self): return self.title def __eq__(self, other): if self.store_id == other.title: return True else: return False def change_description(self, description=""): if not description: description = raw_input("Please give me a description:") self.description = description def change_price(self, price = -1): while price < 0: price = raw_input("Please give me the new price [X.XX]: ") try: price = float(price) break except: print "I'm sorry but {} isn't valid.".format(price) self.price = price def change_title(self, title=""): if not title: title = raw_input("Please give me a new title: ") self.title = title class Book(InventoryItem): def __init__(self, title, description, price, format, author, store_id): super(Book, self).__init__(title=title, description = description, price = price, store_id=store_id) self.format = format self.author = author def __str__(self): book_line = "{title} by {author}".format(title = self.title, author = self.author) return book_line def __eq__(self, other): if self.title == other.title and self.author == other.author: return True else: return False def change_format(self, format): if not format: format = raw_input("Please give me the new format: ") self.format = format def change_author(self, author): if not author: author = raw_input("Please give me the enw author: ") class OperatingSys(InventoryItem): def __init__(self, InventoryItem, title, price, description, opsys, rating, store_id): super(OperatingSys, self).__init__(title=title, price=price, description=description, store_id=store_id) self.opsys = opsys self.rating = rating def __str__(self): opsys_line = "{title} for {OpSys}, price is {price}".format(title = self.title, OpSys=self.OpSys, price = self.price) return opsys_line def __eq__(self, other): if self.title == other.title and self.author == other.author: return True else: return False def change_opsys(self, opsys): if not opsys: opsys = raw_input("Please give me a new Operating System: ") self.opsys = opsys def change_rating(self, rating): if not rating: rating = raw_input("Plese assign the appropriate rating: ") self.rating = rating TheDivision = OperatingSys(title="The Division",description="third person shooter", price=69.99, opsys="", rating="", store_id=3908657) Traceback (most recent call last): File "<pyshell#128>", line 1, in <module> TheDivision = OperatingSys(title="The Division",description="third person shooter", price=69.99, opsys="", rating="", store_id=3908657) TypeError: __init__() takes exactly 8 arguments (7 given)
When you try and create OperatingSys you are passing in 6 parameters — which together with self make 7: OperatingSys( title="The Division", # 1 description="third person shooter", # 2 price=69.99, # 3 opsys="", # 4 rating="", # 5 store_id=3908657 # 6 ) But your definition requires 7 (8 including self): def __init__(self, InventoryItem, title, price, description, opsys, rating, store_id): I suspect that the InventoryItem there is a mistake — you don't need to include the parent class as a parameter in the init definition. def __init__(self, title, price, description, opsys, rating, store_id):