I keep getting this error:
<__main__.product object at 0x0231A7B0>
from the code:
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlist(self):
x = ''
for i in self.cartlist:
x = i, "/n"
return x
instead of executing the function prntlist it displays that error
full code:
class product(object):
name = ''
price = 0
def __init__(self, name, price):
self.name = name
self.price = price
def prnt(self):
print("\n**********************************************************")
print("Item\t\t\t Price")
print(self.name,"............ $", self.price)
print("\n**********************************************************")
def prntline(self):
x = self.name + ".........." + self.price
return x
class cart(object):
totalprice = 0
cartlist = []
def __init__(self):
self.totalprice = totalprice
self.cartlist = []
def setprice(self):
totprice = self.totalprice
for i in self.cartlist:
self.totalprice += i.price
return totprice
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlinecart(self):
print("You have purchased: ", self.prntlist())
def prntlist(self):
x = ''
for i in self.cartlist:
x = i, "/n"
return x
def additem(self, item):
self.cartlist.append(item)
print("Ah, fresh out. But we can have it shipped to your house next week")
Ok, I made your example work for me, just to see what is happening:
class product(object):
name = ''
price = 0
def __init__(self, name, price):
self.name = name
self.price = price
def prnt(self):
print("\n**********************************************************")
print("Item\t\t\t Price")
print(self.name,"............ $", self.price)
print("\n**********************************************************")
def prntline(self):
x = self.name + ".........." + self.price
return x
class cart(object):
totalprice = 0
cartlist = []
def __init__(self):
self.totalprice = 0
self.cartlist = []
def setprice(self):
totprice = self.totalprice
for i in self.cartlist:
self.totalprice += i.price
return totprice
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlinecart(self):
print("You have purchased: ", self.prntlist())
def prntlist(self):
x = ''
print('fff')
for i in self.cartlist:
x = i, "/n"
return x
def additem(self, item):
self.cartlist.append(item)
print("Ah, fresh out. But we can have it shipped to your house next week")
mycart = cart()
RL = product("Red Leicester", 13.99)
RL.prnt()
mycart.additem(RL)
mycart.prnt()
The output is:
**********************************************************
Item Price
Red Leicester ............ $ 13.99
**********************************************************
Ah, fresh out. But we can have it shipped to your house next week
**********************************************************
fff
(<__main__.product object at 0x7ffbe52609e8>, '/n')
Grand total $ 0
**********************************************************
It seems that you ask about this: <__main__.product object at 0x7ffbe52609e8>. As I wrote in the first comment, this is because you are making tuple, not a string when with the following line x = i, "/n".
Related
I'm learning python here:
I have created this cars class below and I want to that result go to the list.
What is the most efficiency way to do it?
class Car:
def __init__(self, brand="", price=""):
self.brand = brand
self.price = price
def __str__(self):
return str(self.brand) + " " + str(self.price)
import random
carslist = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
car1 = Car()
car1.brand = (random.choice(carslist))
car1.price = (random.randint(1000, 10000))
car2 = Car()
car2.brand = (random.choice(carslist))
car2.price = (random.randint(1000, 10000))
car3 = Car()
car3.brand = (random.choice(carslist))
car3.price = (random.randint(1000, 10000))
car4 = Car()
car4.brand = (random.choice(carslist))
car4.price = (random.randint(1000, 10000))
car5 = Car()
car5.brand = (random.choice(carslist))
car5.price = (random.randint(1000, 10000))
print(car1)
I did try it like this cars1 = car1details cars2 = car2details and list [car1details, car2details] but that's not probably the best way to do it.
Thanks for you help!
The below seems to work nice (__repr__ was added since when we print the cars it is used)
import random
class Car:
def __init__(self, brand="", price=0):
self.brand = brand
self.price = price
def __str__(self):
return str(self.brand) + " " + str(self.price)
def __repr__(self):
return str(self.brand) + " " + str(self.price)
cars_models = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
cars = [Car(random.choice(cars_models),random.randint(1000, 10000)) for _ in range(1,8)]
print(cars)
output
[BMW 2008, Volvo 3810, Skoda 8545, Skoda 6715, Ford 9792, Audi 6013, VW 1475]
here is an example of how to append objects to a list by using range()
When you append the Car object you can add variables
class Car(object):
def __init__(self, number):
self.number = number
my_objects = []
for i in range(100):
my_objects.append(Car(i))
from random import randint
class Car():
def __init__(self, name):
self.name= name
self.price = randint(1000, 10000)
def __str__(self):
return f'Car( Name: {self.name} | price {self.price})'
def __repr__(self):
return f'Car( Name: {self.name} | price {self.price})'
carsname = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
cars = []
for name in carsname:
cars.append(Car(name))
Use a basic for :)
I have to set the total_cost variable to be equal to the subtotal variable or the from the product class. However, when I try to derive the value from the class. It gives me an attribute error of AttributeError: 'Product' object has no attribute '_Product__total_price'. I am implementing where you apply the promo code then it will deduct the total price from the cart.
This is init.py and functions used.
#app.route('/applyPromo/<string:id>/', methods=['GET','POST'])
def apply_promo(id):
promotions_dict = {}
db = shelve.open('promotions.db','w')
promotions_dict = db['Promotions']
total_cost = 100
hidden = True
applied = True
click = True
get_from_class = False
print(promotions_dict)
promotions = promotions_dict.get(UUID(id))
db = shelve.open('storage.db', 'r')
product_dict = db['products']
for key in product_dict:
product = product_dict[key]
total_cost = product.get_total_price()
print(total_cost)
#when user apply promo, promo will get deleted from the list/dictionary of promos they have.
if promotions["type"] == 1:
total_cost = total_cost - 10
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 2:
total_cost = total_cost - 5
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 3:
total_cost = (70/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 4:
total_cost = (80/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 5:
total_cost = (85/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
else:
total_cost = (90/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
db['Promotions'] = promotions_dict
db.close()
db.close()
print(promotions_dict)
session['promotion_applied'] = promotions["id"]
return render_template("generatePromo.html", total_cost=total_cost,applied=applied, promotions_dict=promotions_dict,hidden=hidden,promotions=promotions,get_from_class=get_from_class, click=click)
#app.route('/shopping_cart')
def shopping_cart():
# session.clear()
error = None
cart_items = []
quantity_list = []
subtotal = 0
db = shelve.open('storage.db', 'r')
product_dict = db['products']
db.close()
for products in session:
item = product_dict.get(products)
cart_items.append(item)
if None in cart_items:
cart_items.remove(None)
quantity_list.append(session[products])
if products in quantity_list:
quantity_list.remove(products)
for i in range(len(cart_items)):
cart_items[i].set_purchased_quantity(quantity_list[i])
# set total price for single item
item_total = int(cart_items[i].get_price()) * int(cart_items[i].get_purchased_quantity())
cart_items[i].set_total_price(item_total)
# set total price of all items in cart
subtotal += item_total
print('QTY LIST', quantity_list)
print('CART', cart_items)
if not cart_items:
error = "Cart Is Empty"
return render_template('shoppingcart.html', products_list=cart_items, error=error, subtotal=subtotal)
This is the product class.
from uuid import uuid4
class Product:
def __init__(self, name, price, quantity, color, vase, remarks):
self.__product__id = str(uuid4())
self.__name = name
self.__price = price
self.__quantity = quantity
self.__color = color
self.__vase = vase
self.__remarks = remarks
self.__purchased_quantity = 0
self.__total_price = 0
def get_product_id(self):
return self.__product__id
def get_name(self):
return self.__name
def get_price(self):
return self.__price
def get_quantity(self):
return self.__quantity
def get_color(self):
return self.__color
def get_vase(self):
return self.__vase
def get_remarks(self):
return self.__remarks
def get_image(self):
return self.__image
def get_purchased_quantity(self):
return self.__purchased_quantity
def get_total_price(self):
return self.__total_price
def set_name(self, name):
self.__name = name
def set_price(self, price):
self.__price = price
def set_quantity(self, quantity):
self.__quantity = quantity
def set_color(self, color):
self.__color = color
def set_vase(self, vase):
self.__vase = vase
def set_remarks(self, remarks):
self.__remarks = remarks
def set_image(self, image):
self.__image = image
def set_purchased_quantity(self, purchased_quantity):
self.__purchased_quantity = purchased_quantity
def set_total_price(self, total_price):
self.__total_price = total_price
This is the traceback for the error.
Traceback
Leading double underscores should not be used as you are using them to define attributes of your class - single underscores is conventional. The problem with using leading double underscores is that the interpreter "mangles" the names of those attributes to avoid a subtle problem with inheritance, but leading to the problem, I believe, you are seeing. Here is a good read on the subject.
def forecast(bank, years):
class Bank:
def __init__(self, name):
self.name = name
self.mark_cap = 0
self.acc_list = []
self.age = 0
def lend(self, principal, ann_inc):
self.mark_cap -= principal
def forward_year(self):
self.age += 1
def back_year(self):
if self.age == 0:
self.age = 0
self.age -= 1
def show_high(self):
print(Bank.acc_list[0])
class Account:
def __init__(self, ID, password):
self.ID = ID
self.password = password
if len(password) < 5:
print('Password must be at least 5 characters')
self.amount = 0
self.interest = 0.0175
self.acc_org = [ID, password, self.amount, self.interest]
def deposit(self, x):
self.amount += x
self.acc_org[2] = self.amount
def withdraw(self, y):
self.amount -= y
self.acc_org[2] = self.amount
def threshold(self):
if self.amount >= 1000000:
self.interest = 0.02
def comp_int(self, n):
self.threshold()
self.amount *= (1 + self.interest)**n
self.acc_org[2] = self.amount
def show_amount(self):
print(self.amount)
def add_2_bank(self, name):
bank_name = name
bank_name.acc_list.append(self.acc_org)
X = Bank('Bank of china')
Account1 = Account('12345', '12345')
Account1.deposit(200)
Account1.comp_int(2)
Account1.add_2_bank(X)
X.show_high()
The error that I am getting is that my 'Bank' object (X) has no attribute acc_list(). Someone please help me.
In the show_high method, modify Bank.acc_list to self.acc_list. Only static properties can be used like Bank.*.
I Have a class in which a function returns a df , when I try to fetch the values in the Ui_MainWindow class the df is empty.
class Trade():
def __init__(self,date: pd.datetime, quantity: np.float32, price: np.float32):
self.date = date
self.quantity = quantity
self.price = price
def printT(self):
return print('Quantity: %i, Price: %f'%(self.quantity, self.price)
class Isin():
print('dbhfjf')
def __init__(self, isin, notinalPerQuantity, listOfTrades):
self._isin = isin
self._notinalPerQuantity = notinalPerQuantity
self._listOfTrades = listOfTrades
def mtm(self, trade):
return trade.quantity*trade.price*self._notinalPerQuantity
def __next__(self):
return self._listOfTrades.__next__()
def __iter__(self):
return self._listOfTrades.__iter__()
class transactionAccounting():
print('plpl')
def __init__(self, isin):
print('Initialize trade que')
self._Isin = isin
self._notinalPerQuantity = isin._notinalPerQuantity
self._trades = isin._listOfTrades
t0 = self._trades[0]
self._avgprice = 0
self._quantity = 0
self._pnl = 0
self._bookvalue =0
self.quantity=[]
self.pnl=[]
self.amount=[]
self.average=[]
global oo
oo = pd.DataFrame(columns = ['Balance quantity', 'Balance Amount','Average Price','Realized Profits'])
def printStat(self):
print('Balance Quantity: %i, AvgPrice: %f, Profit & Loss: %f, Balance amount: %f'%(self._quantity,
self._avgprice,
self._pnl,
self._bookvalue))
for x in range(1):
self.quantity.append(self._quantity)
last=self.quantity
s=pd.Series(last)
s=list(s)
print(s)
#oo['Balance quantity']=s
for j in range(1):
self.amount.append(self._bookvalue)
am=self.amount
amount=pd.Series(am)
amount=list(amount)
print(amount)
#oo['Balance Amount']=amount
for k in range(1):
self.average.append(self._avgprice)
ap=self.average
app=pd.Series(ap)
app=list(app)
print(app)
#oo['Average Price']=app
for i in range(1):
self.pnl.append(self._pnl)
pl=self.pnl
p=pd.Series(pl)
p=list(p)
print(p)
#oo['Realized Profits']=p
#df=pd.DataFrame(s,columns=['Balance Quantity'])
#df=pd.DataFrame(amount,columns=['Balance Amount'])
#df=pd.DataFrame(app,columns=['Average Price'])
#df=pd.DataFrame(p,columns=['Realized Profits'])
#print(df)
self.dff = pd.DataFrame({'Balance Quantity': s,'Balance Amount': amount,'Average Price ': app,'Realized Profit':p})
print(self.dff)
return self.dff
def buy(self, trade):
raise NotImplementedError
def sell(self, trade):
raise NotImplementedError
def dff(self):
return self.dff
class FifoAccount(transactionAccounting):
def __init__(self, trades):
transactionAccounting.__init__(self, trades)
self._deque = deque()
for trade in self._trades:
if trade.quantity>=0:
self.buy(trade)
else:
self.sell(trade)
def buy(self, trade):
print('Buy trade')
trade.printT()
self._deque.append(trade)
self._bookvalue += self._Isin.mtm(trade)
self._quantity += trade.quantity
self._avgprice = self._bookvalue / self._quantity / self._notinalPerQuantity
#avg_price=self._avgprice
buy_quant=self._quantity
bal_buy=self._bookvalue
pnl=self._pnl
self.printStat()
def sell(self, trade):
print('Sell trade')
trade.printT()
sellQuant = -trade.quantity
while(sellQuant>0):
lastTrade = self._deque.popleft()
price = lastTrade.price
quantity = lastTrade.quantity
print('Cancel trade:')
lastTrade.printT()
if sellQuant >= quantity:
self._pnl += -(price - trade.price)*quantity*self._notinalPerQuantity
self._quantity -= quantity
self._bookvalue -= price * quantity * self._notinalPerQuantity
sellQuant -= quantity
else:
self._pnl += -(price - trade.price)*sellQuant*self._notinalPerQuantity
self._quantity -= sellQuant
self._bookvalue -= price * sellQuant * self._notinalPerQuantity
lastTrade.quantity -= sellQuant
self._deque.appendleft(lastTrade)
sellQuant = 0
self.printStat()
assert(self._quantity > 0)
class Ui_MainWindow(object):
self.ef=pd.read_excel('D:\\PMS\\Port 5\\Portfolio Ledger\\Mutual Fund\\AXIS.xlsx')
self.ef.replace('nan', np.nan, inplace=True)
numberOfRows = len(self.ef.index)
e={'Date':[],'Quantity':[],'Price':[]}
e = pd.DataFrame(e)
el=[]
row = 0
i = 0
while i < numberOfRows:
if self.ef.isnull().iat[row,1] != True:
adding = pd.DataFrame({"Date":[self.ef.iat[row,0]],
"Quantity":[self.ef.iat[row,1]],
"Price":[self.ef.iat[row,2]]})
e = e.append(adding, ignore_index=True)
f=e['Date'].iloc[-1]
i += 1
row += 1
Date=e['Date'].iloc[-1]
Quantity=e['Quantity'].iloc[-1]
Price=e['Price'].iloc[-1]
print(Date)
print(Quantity)
print(Price)
#s=pd.Series(['Date','Quantity','Price'])
#print(s[0])
el.append(Trade(pd.to_datetime(Date,format='%d.%m.%Y'), Quantity, Price))
else:
adding = pd.DataFrame({"Date": [self.ef.iat[row, 0]],
"Quantity": [self.ef.iat[row, 3]*(-1)],
"Price": [self.ef.iat[row, 4]]})
e = e.append(adding, ignore_index=True)
#print(e.tail(1))
i += 1
row += 1
Date=e['Date'].iloc[-1]
Quantity=e['Quantity'].iloc[-1]
Price=e['Price'].iloc[-1]
print(Date)
print(Quantity)
print(Price)
#s=pd.Series(['Date','Quantity','Price'])
#print(s[0])
el.append(Trade(pd.to_datetime(Date,format='%d.%m.%Y'), Quantity, Price))
b = Isin('bond', 1, el)
#print('111111')
trans = FifoAccount(b)
#print(self.dff)
avds=transactionAccounting(b)
fff=avds.printStat()
print(fff)
When I try to print(fff) in the Ui_MainWindow it is empty, I do not understand how to call self.dff in the Ui_MainWindow, even the function printStat() return the df and when I print in the df has four columns filled with the FIFO logic
Ui_MainWindow does not have access to the dff variable. Notice that the transactionAccounting() class is inside the Isin() class.
You've defined an Isin() class in the following line inside your Ui_MainWindow:
b = Isin('bond', 1, el)
You could technically initiate the transactionAccounting() class like so:
b = Isin('bond', 1, el)
b.transactionAccounting(your_arguments)
self.dff = b.dff
#or
ta = IsIn.transactionAccounting(your_arguments)
self.dff = b.dff
However, I don't believe the indentation of transactionAccounting() was intentional. So, therefore, I would recommend to tab-back all of the code in transactionAccounting() by one spacing, and initialize it in your Ui_MainWindow:
ta = transactionAccounting(your_arguments)
self.dff = ta.dff
However, this is not needed:
def dff(self):
return self.dff
Big tip: Make your workspace spacing a tab as opposed to some n numbers of spaces. Issues like this will become more apparent if it was indeed a spacing mistake, as I suspect.
I'm trying to unit test purchaseItem when there is no positive amount of given product and find_price_of_given_id methods in my Automat class.
import unittest
from Automat import Automat
from Bank import Bank
from Item import Item
from exceptions.NoItemException import NoItemException
class AutomatTest(unittest.TestCase):
def test_checkPriceOfGivenID(self):
bank = Bank()
automat = Automat(bank)
Cola = Item(2)
automat.add_object(Cola)
self.assertEqual(automat.find_price_of_given_id(30), 2)
def test_checkIfPurchaseItemCanBeProcessedWhenNoProduct(self):
bank = Bank()
automat2 = Automat(bank)
Soda = Item(2, 0)
automat2.add_object(Soda)
self.assertEqual(automat2.purchaseItem(30), "Given amount it too small and " \
"no item with " + str(30) + " in automat!")
if __name__ == '__main__':
unittest.main()
If I run test one by one, both are passed. If I run the whole class then it says thattest_checkPriceOfGivenID is failed :
Testing started at 14:12 ...
C:\Users\Admin\PycharmProjects\vending-machine\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2018.3.4\helpers\pycharm\_jb_unittest_runner.py" --path C:/Users/Admin/PycharmProjects/vending-machine/AutomatTest.py
Launching unittests with arguments python -m unittest C:/Users/Admin/PycharmProjects/vending-machine/AutomatTest.py in C:\Users\Admin\PycharmProjects\vending-machine
Ran 2 tests in 0.004s
Error
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "C:\ProgramData\Anaconda3\lib\unittest\case.py", line 615, in run
testMethod()
File "C:\Users\Admin\PycharmProjects\vending-machine\AutomatTest.py", line 15, in test_checkPriceOfGivenID
self.assertEqual(automat.find_price_of_given_id(30), 2)
File "C:\Users\Admin\PycharmProjects\vending-machine\Automat.py", line 28, in find_price_of_given_id
raise NoItemException
exceptions.NoItemException.NoItemException
FAILED (errors=1)
Process finished with exit code 1
Automat class
from Item import Item
from exceptions.NoItemException import NoItemException
from exceptions.NoProperAmountException import NoProperAmountException
from Coin import Coin
from decimal import *
class Automat:
item_id = 30
def __init__(self, _bank, objects=None):
self.bank = _bank
if objects is None:
objects = {}
self.objects = objects
self.purchaseItemBank = []
def add_object(self, obj: Item):
id_to_assign = Automat.item_id
self.objects.update({id_to_assign: obj})
Automat.item_id = Automat.item_id + 1
return id_to_assign
def find_price_of_given_id(self, item_id):
if self.objects.get(item_id) is not None:
return self.objects.get(item_id).get_price()
else:
raise NoItemException
def find_amount_of_given_id(self, item_id):
if self.objects.get(item_id) is not None:
return self.objects.get(item_id).get_amount()
else:
raise NoItemException
def checkIfAmountIsPositive(self, item_id):
if self.objects.get(item_id) is not None:
var = True if self.objects.get(item_id).get_amount() > 0 else False
return var
else:
raise NoItemException
def withdrawItem(self, item_id):
self.objects.get(item_id).decrease()
def purchaseItem(self, item_id):
sumOfCoins = 0
if 30 <= item_id <= 50:
lista = []
for i in self.purchaseItemBank:
lista.append(i)
sumOfCoins += i.getCoinValue()
priceOfGivenProduct = self.find_price_of_given_id(item_id)
if sumOfCoins < priceOfGivenProduct:
if not self.checkIfAmountIsPositive(item_id):
return "Given amount it too small and " \
"no item with " + str(item_id) + " in automat!"
else:
raise NoProperAmountException
else:
if not self.checkIfAmountIsPositive(item_id):
return "No item with " + str(item_id) + " in automat!"
a = round(abs(Decimal(priceOfGivenProduct) - sumOfCoins), 2)
listaCopy = self.bank.getSortedBankListWithCoins()
if a > 0:
if len(listaCopy) == 0:
return "Nie mozna wydac"
for i, v in enumerate(self.bank.bank):
if a == 0:
break
elif a >= v.getCoinValue():
a = a - v.getCoinValue()
listaCopy.remove(v)
elif a < v.getCoinValue():
continue
if i + 1 == (len(self.bank.bank)):
return "Nie mozna wydac"
if a > 0:
return "Nie mozna wydac"
self.bank.bank = listaCopy.copy()
self.withdrawItem(item_id)
for iterator in lista:
self.bank.addMoney(iterator)
return "Wydano towar"
else:
raise NoItemException
Item class:
class Item:
def __init__(self, price, amount=5):
self.amount = amount
self.price = price
def get_price(self):
return self.price
def get_amount(self):
return self.amount
def decrease(self):
self.amount -= 1
def __str__(self):
return f"{self.amount} # {self.price}"
Bank class:
class Bank:
def __init__(self):
self.bank = []
def addMoney(self, value):
self.bank.append(value)
def getSumBank(self):
return sum(value.getCoinValue() for value in self.bank)
def getSumOfGivenCoins(self, *args):
suma = 0
for i in args:
suma += i.getCoinValue()
return suma
def getSortedBankListWithCoins(self):
self.bank.sort(key=lambda x: x.getCoinValue(), reverse=True)
listaCopy = self.bank.copy()
return listaCopy
Here:
class Automat:
item_id = 30
item_id is a class attribute - it's shared between all instances of Automat, which is probably how the tests are interfering with one another.
Update:
One way to fix the problem would be to reset the item_id in a setUp method.
What you need is to convert item_id to an instance variable:
class Automat:
def __init__(self, _bank, objects=None):
self.item_id = 30
# rest of init here ...
def add_object(self, obj: Item):
id_to_assign = self.item_id
self.objects.update({id_to_assign: obj})
self.item_id += 1
return id_to_assign
Now all ids will start at 30 and your unit tests will be able to find these items.