Unable to display data with __str__ - python

This code is part of a larger program .. I am trying to generate a summary that displays the data taken from a user
class Mbilling:
def __init__(self, income, debit = 0, rent = 745):
self.income = income
self.debit = debit
self.rent = rent
class Display(Mbilling):
def listMbilling(self):
self.m = f"""
------------------------------------
--> Income = {self.income}
--> Debit = {self.debit}
--> Rent = {self.rent}
------------------------------------
"""
def __str__(self):
return self.m
and i am getting this error:
Traceback (most recent call last):
File "G:\Engineering\#ZicX\#Programming in Python\Basic Python\Tutorials\test.py", line 25, in <module>
receipt = Display()
TypeError: __init__() missing 1 required positional argument: 'income'
When i try these command:
d1 = Mbilling(5000, 0, 750)
receipt = Display()
print(receipt)
Need help to understand what's wrong ,, thanks !

I feel that the issue here is a matter of class inheritance. I am by no means a super() expert but here's what I can contribute:
Here is one example:
class MethodOne:
def __init__(self):
self.param_one = "Car"
self.param_two = 200
class MethodTwo(MethodOne):
def __init__(self):
super().__init__()
def __str__(self):
self.string_one = f"I have a {self.param_one}."
self.string_two = f"{self.param_two} minus 100 equals {self.param_two - 100}!"
return self.string_one + "\n" + self.string_two
And here is another example that more closely relates to what you are looking to achieve.
class Mbilling:
def __init__(self, income = 0, debit = 0, rent = 745):
self.income = income
self.debit = debit
self.rent = rent
print("Hi there. I am the parent")
class Display(Mbilling):
def __init__(self, income, debit, rent):
print("Hi, I am the child")
super().__init__()
def listMbilling(self):
self.m = f"""
------------------------------------
--> Income = {self.income}
--> Debit = {self.debit}
--> Rent = {self.rent}
------------------------------------
"""
def __str__(self):
self.listMbilling()
return self.m
d1 = Display(23, 40, 745)
print(d1)
Also, this link is super ;) useful https://www.educative.io/edpresso/what-is-super-in-python

Related

Product Inventory program that takes products with an ID, quantity, and price and uses an Inventory class to keep track of the products

The Product class seems to work fine but I'm trying to figure out how to get the Inventory class to separate each product into there specific categories. I feel like I'm close but whenever I try and print out the inventory it just shows where it's stored in memory and doesn't actually print anything out. The output i receive when running is at the bottom. I want it to print out the actual products and data, not the instance of it stored in memory.
class Product:
def __init__(self, pid, price, quantity):
self.pid = pid
self.price = price
self.quantity = quantity
def __str__(self):
#Return the strinf representing the product
return "Product ID: {}\t Price: {}\t Quantity: {}\n".format(self.pid, self.price, self.quantity)
def get_id(self):
#returns id
return self.pid
def get_price(self):
#returns price
return self.price
def get_quantity(self):
#returns quantity
return self.quantity
def increase_quantity(self):
self.quantity += 1
def decrease_quantity(self):
self.quantity -= 1
def get_value(self):
value = self.quantity * self.price
return 'value is {}'.format(value)
product_1 = Product('fishing', 20, 10)
product_2 = Product('apparel', 35, 20)
class Inventory:
def __init__(self, products):
self.products = products
self.fishing_list = []
self.apparel_list = []
self.value = 0
def __repr__(self):
return "Inventory(products: {}, fishing_list: {}, apparel_list: {}, value: {})".format(self.products, self.fishing_list, self.apparel_list, self.value)
def add_fishing(self):
for product in self.products:
if product.get_id() == 'fishing':
self.fishing_list.append(product)
return '{} is in the fishing section'.format(self.fishing_list)
def add_apparel(self):
for product in self.products:
if product.get_id() == 'apparel':
self.apparel_list.append(product)
return '{} is in the apparel section'.format(self.apparel_list)
inventory_1 = Inventory([product_1, product_2])
inventory_1.add_fishing()
print(inventory_1)
OUTPUT = Inventory(products: [<main.Product instance at 0x10dbc8248>, <main.Product instance at 0x10dbc8290>], fishing_list: [<main.Product instance at 0x10dbc8248>], apparel_list: [], value: 0)
You need to specify how an object of the class Inventory should be printed.
To do this you need to implement at least one of the following functions in your class.
__repr__
__str__
This answer helps, which of both you should use: https://stackoverflow.com/a/2626364/8411228
An implementation could look something like this:
class Inventory:
# your code ...
def __repr__(self):
return str(self.products) + str(self.fishing_list) + str(self.apparel_list) + str(self.value)
# or even better with formatting
def __repr__(self):
return f"Inventory(products: {self.products}, fishing_list: {self.fishing_list}, apparel_list: {self.apparel_list}, value: {self.value})
Note that I used in the second example f strings, to format the output string.

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

Simple class Property Update

I have a class where I'm expecting this:
print(rithesh.amount) = 150.
How can I do this?
Here is my code:
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
def add_amount(self, amount):
self.amount = amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
You can declare your amount variable in your __init__ method as 0. Then make a small change in your add_amount method.
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
self.amount = 0
def add_amount(self, amount):
self.amount += amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
output
150
The actual way of having properties in python is by using #property decorator
for example, in your class:
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
#property
def add_amount(self):
return self.add_amount
#add_amount.setter
def add_amount(self, amount):
self.add_amount = amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount = 150
print(rithesh.add_amount)
Got how to do it.
i have to declare the value self.amount = 0 during initialization.
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
self.amount = 0
def add_amount(self, amount):
self.amount += amount
rithesh = Customer("Ritehsh", "8892398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
hence getting output as print(rithesh.amount) = 150
What is happening is that when you call add_amount you are not adding the value to self.amount you are just setting it.
Just change the definition of add_amount from:
self.amount = amount
to:
self.amount += amount
And add to the __init__ method:
self.amount = 0

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):

Pass attribute through multiple classes in Python

I want to pass an attribute of tax return data to a tax calculator I have created. For example, I would like to pass salaries_wages of 100000. Here what I have so far but I can't seem to get it to work:
class TaxReturn:
def __init__(self, income = None, stat_adj = None, AGI = None):
income = income or ['salaries_wages', 'interest_received', 'tax_exempt_interest_income', 'dividend_AGI', 'qualified_dividend']
stat_adj = stat_adj or ['deductible_IRA_payments', 'student_loan_interest_deduc', 'education_expenses', 'tuition_fees_deduc',
'self_employ_deduc', 'self_employ_healthinsur_deduc', 'domestic_production_deduc']
AGI = AGI or 'AGI'
self.income = 'income'
self.stat_adj = 'stat_adj'
self.AGI = 'AGI'
class Income:
def __init__(self= None, salaries_wages= None, intr_rec= None, txexem_intinc= None, dividend_AGI= None, qualified_dividend= None):
salaries_wages = salaries_wages or 'salaries_wages'
intr_rec = intr_rec or 'intr_rec'
txexem_intinc = txexem_intinc or 'txexem_intinc'
dividend_AGI = dividend_AGI or 'dividend_AGI'
qualified_dividend = qualified_dividend or 'qualified_dividend'
class TaxCal:
def __init__(self):
self.brackets = {(0,8025):0.10, (8025,32550):.15, (32550,78850):.25, (78850, 164550):.28, (164550,357700):.33, (357700,371815):.35, (371815, sys.maxsize):.396}
def taxcal (self, salaries_wages):
tax = 0
for bracket in self.brackets:
if salaries_wages > bracket[0]:
for _ in range(bracket[0], min(salares_wages, bracket[1])):
tax += self.brackets[bracket]
return tax
tx = TaxReturn()
inc = Income()
txcal = TaxCal()
print(tx.inc.txcal.taxcal(100000)), format(round(tx.inc.txcal.taxcal(100000), 2)
Take care of your indentation, and class design. I don't know why you are assigning unknown variables in your class. Unless you make it part of class, it is useless:
import sys
class Income:
def __init__(self= None, salaries_wages= None, intr_rec= None, txexem_intinc= None, dividend_AGI= None, qualified_dividend= None):
self.salaries_wages = salaries_wages or 'salaries_wages'
self.intr_rec = intr_rec or 'intr_rec'
self.txexem_intinc = txexem_intinc or 'txexem_intinc'
self.dividend_AGI = dividend_AGI or 'dividend_AGI'
self.qualified_dividend = qualified_dividend or 'qualified_dividend'
class TaxCal:
def __init__(self):
self.brackets = {(0,8025):0.10, (8025,32550):.15, (32550,78850):.25, (78850, 164550):.28, (164550,357700):.33, (357700,371815):.35, (371815, sys.maxsize):.396}
def taxcal (self, inc):
tax = 0
for bracket in self.brackets:
if inc.salaries_wages and inc.salaries_wages > bracket[0]:
for _ in range(bracket[0], min(inc.salaries_wages, bracket[1])):
tax += self.brackets[bracket]
return tax
tx = TaxReturn()
inc = Income(100000)
txcal = TaxCal()
print(txcal.taxcal(inc))

Categories

Resources