how to setup an accumulator variable? - python

First of all, I am writing a code to print inventory of Ikea from a file that has lines like this,
F,301.841.73,9.99,HOLMÖ,Floor lamp - gives a soft mood light,none,75,116,22,2.2
where the third one "9.99" is the price of that furniture item. i have getter and setter for the price variable as well.
def setPrice(self, f_price):
self.__price = f_price
def getPrice(self):
return self.__price
there is main class called Furniture and other sub-classes for items like "BED", "NIGHTSTAND", "ARMCHAIR" etc..
there is a UNIT test framework for these classes. where it creates a list, them opens the file and using loop , it adds all the variables for furniture item like type, an article number, a price, a Swedish-sounding name, a basic description, and optionally, a colour from Furniture class as well as sub variables from sub class to list.
then, AT last, we need to count Total value of inventory. where I initialized a Total_value variable to 0.
total_value = 0
for furniture_item in inventory:
print(str(furniture_item)) # print the item
print("="*30) # print a separator
# ADD THE PRICE OF THE ITEM TO THE ACCUMULATOR VARIABLE
total_value += (value)
when I try to get price from getPrice function:
price = Furniture.getPrice
total_value += price
it gives me error like this:
*****Error***
Traceback (most recent call last):
File "__tester__.python3", line 212, in <module>
total_value += price
TypeError: unsupported operand type(s) for +=: 'int' and 'function'**
when i do like this:
Furniture.getPrice = price
total_value += price
It gives me the value of **Total Inventory Value: 3184.0**. But, the value expected is **Total Inventory Value: 1432.91**, I don't know what wrong I am doing.
If anyone can suggest to me how to get this expected value, that would be great!!!

I'm guessing you want
total_price += furniture_item.getPrice()

Related

How to get a total from with "Class" in python, then calling it into another file main()?

My assignment is : Assume you sell t-shirts ( or any other item), and all t-shirts cost the same, they all have the same price
Define a class called Sale. The first line of the constructor would only have 3 arguments: self, item and quantity. In addition, the constructor has an attribute for the price and an attribute to hold the total for the sale.
The program assumes the same price for every item, so you can initialize the price in init using the price of your choice. Just like we did with the car example I showed in the lecture, where the speed attribute was initialized to zero in init, you could initialize total at total to zero
The class should have 4 methods to:
A method to calculate the total
A method to return the total
A method to return the item
A method to return quantity
The program importing the file with this class needs to create an instance of the Sale class. Assuming, the file with the class definition is sale.py and the class is Sale, it would look something like this
new_sale = sale.Sale('Men medium blue', 10)
When I run the program that creates the class instance, assuming the price in the class was set to 9.99, the output would look something like this
new_sale = sale.Sale('Men medium blue', 10)
The total for 10 t-shirts Men medium blue is $ 99.9
'''class Sale:
def __init__(self,item,quantity):
self.item=item
self.quantity=quantity
self.total=self.price*self.quantity
self.price=10
def get_item(self):
return self.item
def get_quantity(self):
return self.quantity
def get_total(self):
return self.total
'''
This is my main function in another file, I'm trying to get the user input quantity to multiply by the set price ($10) in Class
'''
import sale
def main():
itemQ=input("Please enter type of t-shirt: ")
quanT=int(input("Please insert number of t-shirt you wish to buy: "))
theSale= sale.Sale(itemQ, quanT)
print("The item is ", theSale.get_item(), " and a quantity of ", theSale.get_quantity(), "and total of ", theSale.get_total())
main()
'''
A couple minor changes should get it working:
# sale.py
def __init__(self, item, quantity):
self.item=item
self.quantity=quantity
self.price=10
self.total=self.price*self.quantity # you have to define price before you use it to calculate the total
# add these two lines at the end of you main .py file
if __name__ == '__main__':
main()
See python docs on main method: main

Trying to change certain values in objects while using file access

I'm trying to change a specific part of an object. Specifically, I'm trying to subtract a certain value from the acc. Where then the change is recorded on an already created text file.
Traceback (most recent call last):
File "main.py", line 152, in <module>
start()
File "main.py", line 141, in start
withdraw(id,input("How much do you want to withdraw?"))
File "main.py", line 55, in withdraw
if allCustom[d].hkid== x:
TypeError: list indices must be integers or slices, not Customer
class Customer:
def __init__(self, name, date, address, hkid, acc):
self.name = name
self.date = date
self.address = address
self.hkid = hkid
self.acc = acc
allCustom = [customer1, customer2, customer3, customer4, customer5]
customer1 = Customer ("Sarah Parker","1/1/2000","Hong Kong, Tai Koo,Tai Koo Shing Block 22,Floor 10, Flat 1", "X1343434","2222")
def withdraw (x,y):
global allCustom
count = 0
for d in allCustom:
if allCustom[d].hkid== x:
if int(allCustom[d].acc) >= int(y):
allCustom[d] = Customer (allCustom[d].name, allCustom[d].date, allCustom[d].address, allCustom[d].hkid, str(int(allCustom[d].acc)-int(y)))
print("Success! Please collect your money.")
break
else:
print("Sorry but you have inseffecient funds to withdraw $"+y)
elif count == len(allCustom):
print("Your HKID does not match any account in our database. Returning to starting screen")
else:
count +=1
def UpdateFile():
global allCustom
OutFile=open("CustomInfo.txt", "w")
for c in allCustom:
OutFile.write(f"\nName:{c.name}\n")
OutFile.write(f"Birth Date:{c.date}\n")
OutFile.write(f"Address:{c.address}\n")
OutFile.write(f"HKID:{c.hkid}\n")
OutFile.write(f"Account value:{c.acc}\n")
OutFile.close()
UpdateFile()
As #furas said in a comment, just use:
if d.hkid== x:
This is because for d in allCustom: will iterate over the list allCustom binding the variable d to each item of the list in turn. At this point d is a Customer object and you can access its attributes. You therefore do not need to try to lookup the customer in the list because you already have a reference to it in d.
You will need to correct the other instances of allCustom[d] in the rest of your code.
You probably have this confused because of this Python idiom:
for i in range(len(allCustom)):
if allCustom[i].hkid== x:
which uses indices to access the items in the list. The first form for d in allCustom is preferred - it is clearer and more succinct.

Code is looking for attributes in the wrong class

This code's really unfinished, but it's getting there. I'm trying to organize the inputs of an item's name and price to a list, but I'm getting an error caused by the code looking for the _purchases attribute in the Item class instead of the Receipt class. What's causing this?
import datetime
class Item:
def __init__(self,_name="None",_price=0,_taxable="no"):
self._name=_name
self._price=_price
self._taxable=_taxable
def __str__(self):
base="{:-<20}".format(self._name)+"{:->20}".format(self._price)
return base
def getPric(self):
pass
def getTax(self):
pass
class Receipt:
def __init__(self,_tax_rate=0,_purchases=""):
self._tax_rate=_tax_rate
self._purchases=_purchases
def __str__(self):
pass
def additem(self):
list=self._purchases.append(self)
#Main Program
if __name__=="__main__":
loop="no"
print("Welcome to Receipt Creator")
while True:
name=input("Enter Item name: ")
price=float(input("Enter Item Price: "))
taxable=input("Is the item taxable (yes/no): ")
product=Item(name,price,taxable)
print(product)
print(Receipt.additem(product))
print(list)
loop=input("Add another item (yes/no): ")
if loop=="yes":
continue
else:
break
print("----- Receipt",str(datetime.datetime.now()),"-----")
print(list)
EDIT: Here's the error
Traceback (most recent call last):
File "C:\Users\lucas\Desktop\main.py", line 35, in <module>
print(Receipt.additem(product))
File "C:\Users\lucas\Desktop\main.py", line 23, in additem
list=self._purchases.append(self)
AttributeError: 'Item' object has no attribute '_purchases'
You have a clear idea of what you have, but the execution has a lot of room for improvement.
Let's not touch the Item class, since that is not the one that is causing troubles. But as regards to Receipt, let's create a list for purchases to hold the purchases, and let's define a method (add_item) to populate that list:
class Receipt:
def __init__(self, tax_rate=0):
self.tax_rate = tax_rate
self.purchases = []
def add_item(self, item):
self.purchases.append(item)
Now, you definitely need to instantiate that Receipt class (as opposite as you were doing), so in your main loop you should have something like:
if __name__=="__main__":
print("Welcome to Receipt Creator")
rcpt = Receipt()
while True:
name = input("Enter Item name: ")
price = float(input("Enter Item Price: "))
taxable = input("Is the item taxable (yes/no): ")
product = Item(name, price, taxable)
print(product)
rcpt.add_item(product)
print(rcpt.purchases)
loop = input("Add another item (yes/no): ")
if loop == "yes":
continue
else:
break
print(rcpt.purchases)
Now, some things to note in your previous code:
Unless you want to let other people know that an attribute is meant to be used only inside the definition of a class, there's no actual need to use a leading underscore to name an attribute.
You were trying to print list. Keep in mind that list is a builtin class, so try name your attributes using something different (you can use a trailing underscore, actually. Like list_). Moreover, you were trying to print the list attribute that you had defined in your additem() method, without having instantiated the Receipt class and ask the class for it (with something like instance.list_).
In your __init__ method of the Receipt class that you had defined, you had a default value for _purchases to be "" (an empty string), but that attribute was intended to be a list. (since you were trying to use the append() method after in your additem() method), which makes no sense at all.
#revliscano has an answer that fixes your issues. I will leave the answer to him. I am just going to explain why you got the somewhat confusing error that you got.
looking for _purchases attribute in the Item class
In your class Receipt you have:
class Receipt:
...
def additem(self):
list=self._purchases.append(self)
and were later calling it with:
product=Item(name,price,taxable)
print(product)
print(Receipt.additem(product))
So you are calling additem() on the Receipt class, not on an instance of that class. Normally when you call an instance method, the instance you are calling it with is passed in as the self by python. It did not have an instance since you called it on the class itself, and as a result under the hood python was passing the product in as the self variable because python was treating it like a call on a static class method though it was supposed to be an instance method (i.e. no cls or self arg, and just pass the given arg to the method). So because you called it like Receipt.additem(product), the product was passed as the self.
That meant that when it tried to do the self._purchases.append(self) it was like it was trying to do product._purchases.append(product) and so it was trying to find the _purchases attribute on product. Since product is an instance of the Item class, that is how you get your confusing error message.

Tuple error with class and object

I'm currently working on this,
Design a class Car.
This class has the following attributes: maker, model, and price
The Car class should have methods to return the current values of these attributes. In addition, this class has a method update_price to change the price attribute value.
Design a class called Dealer.
This class has the following attributes: address and inventory. The inventory attribute is a list of Car objects.
The Dealer class should have methods to add a car object to the inventory, remove a car object from the inventory (car removal should be done based on car model), and update the price of a certain car model. This class also has a method that shows the entire inventory and a method that calculates the total value of all cars in the inventory.
In the main function, the program creates a Dealer object, adds multiple cars to the inventory, and shows the current inventory. Then the program removes a car model from the inventory and updates the price for a given car model. At the end, the program displays the entire inventory and the total value of all cars currently in the inventory.
But when I run my code I get
TypeError: descriptor 'append' requires a 'list' object but received a 'tuple'
And I have no idea how to fix this
class Car:
def __init__(self, maker, model, price):
self.__maker=maker
self.__model=model
self.__price=price
def get_model(self):
return self.__model
def get_maker(self):
return self.__maker
def get_price(self):
return self.__price
def create_list(list):
maker=input('Enter Car maker: ')
model=input('Enter Car model: ')
price=float(input('Enter Car price: $'))
account=(maker, model, price)
list.append(account)
def update_price(self):
self.__price=price
return self.__update_price
class Dealer():
def __init__(address, inventory):
self.__inventory=inventory
self.__address=address
def update_price(list):
model=input('Enter car model: ')
account=Car(maker, model, price)
found='false'
for model in list:
if account.get_model() == model:
account.append(price)
found=='true'
if found == 'false':
print('Model Not Found')
return account
def show_inventory(list):
show_inventory=print(account)
def calculate_total_value(list):
print(sum(self.__account.price))
def remove_car(list):
model=input('Model for removal')
found = 'false'
for model in list:
if account.get_model() ==model:
account.remove(model)
found =='true'
if found =='false':
print('Model Not Found')
def get_address(address):
self.__address=address
return self.__address
def main():
address=input('Enter address: ')
account_list=[]
counter=1
manytimes=float(input('How many cars to add? '))
while counter<=manytimes:
counter=counter+1
create_list(list)
show_inventory(account_list)
remove_car(account_list)
show_inventory(list)
update_price(account_list)
show_inventory(account_list)
calculate_total_value(account_list)
main()
Looks like wherever that error is occuring, you're trying to append something to a tuple which is immutable, meaning it can't be changed (in this case, you can't append something to it). A tuple is very similar to a list in that in can store values and be accessed through an index (starting at 0). Wherever you're trying to append something, make sure you're using a list and not a tuple. If it is a tuple, you can convert it to a list using list(tuple_name) and then you should be able to append to it.

Modifying an Attribute's value through method

class UniversityAthletics():
def __init__(self, university_name, sport):
self.name = university_name
self.sport = sport
self.tickets_sold = 10
def tickets_sold(self):
"""This just tells you how many tickets have been sold"""
print(str(self.tickets_sold) + " tickets have been sold")
def describe_athletics(self):
print(self.name.title() + " " + self.sport.title())
def in_season(self):
print(self.sport.title() + " is in season.")
def set_tickets_sold(self, numticket):
"""This sets the number of tickets that have been sold"""
self.tickets_sold = numticket
def increment_tickets_sold(self, moretickets):
"""This increments the number of tickets sold"""
self.tickets_sold += moretickets
athletics = UniversityAthletics('salisbury university', 'soccer')
athletics.set_tickets_sold(20)
athletics.tickets_sold()
athletics.increment_tickets_sold(500)
athletics.tickets_sold()
I tried to make an attribute that sets the number of tickets sold 'set_tickets_sold' and then an attribute that changes the number of the tickets 'increment_tickets_sold' but when I try to set the number of tickets and then call the method 'tickets_sold()' i keep receiving an error.
Traceback (most recent call last): File
"E:/WorWic/IntroToProgramming/chapter9/University Athletics part
2.py", line 29, in
athletics.tickets_sold() TypeError: 'int' object is not callable
What did I do wrong?
Your issue is that tickets_sold is both an attribute and a function name. It's getting the attribute and calling that, rather than the function. I suggest renaming your function to something else.

Categories