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))
Related
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.
I am using Python 3. Here is what my class and inheritance class looks like:
class Vehicle:
def __init__(self,Make,Model,Year,Weight,TripsSinceMaintenance = 0,NeedsMaintenance = False):
self.make = Make
self.model = Model
self.year = Year
self.weight = Weight
self.needsmaintenance = NeedsMaintenance
self.tripssincemaintenance = TripsSinceMaintenance
def repair(self):
self.needsmaintenance = True
self.tripssincemaintenance = 0
class Cars(Vehicle):
def __init__(self,Make,Model,Year,Weight,TripsSinceMaintenance = 0,NeedsMaintenance = False,isdriving = False):
Vehicle.__init__(self,Make,Model,Year,Weight,TripsSinceMaintenance = 0,NeedsMaintenance = False)
self.isDriving = isdriving
def Drive(self):
self.isDriving = True
def Stop(self):
self.isDriving = False
self.tripssincemaintenance += 1
if self.tripssincemaintenance == 100:
self.needsmaintenance = True
This is where I make use of the class:
Car2 = Cars("Mercedes","G-Wagon","2016","2000", 98,False)
Car2.Drive()
Car2.Stop()
print(Car2.year)
print(Car2.model)
print(Car2.make)
print(Car2.isDriving)
print(Car2.needsmaintenance)
print(Car2.tripssincemaintenance)
print(Car2.weight)
The problem is that when self.tripssincemaintenance is printed, it shows 1 instead of 99. Why is that? TIA
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
there are two functions: init and set_info. (full visison shown at the end)
class DefaultNode(object):
def __init__(self, node_name, node_pre= None, node_next = None,
act_func='sign', agg_func='sum', bias=0.0, response=1.0, node_type=None):
...
def set_info(self, node_pre= None, node_next = None, act_func='sign',
agg_func='sum', bias=0.0, response=1.0):
...
Set_info function has many default parameter values. I don't want to rewrite those parameters, which were given in the initializing process.In other words, if one of the parameter is to be set using set_info, the other parameters should remain the same.
For example,
temp_node = DefaultNode("givenname", node_pre = PRE)
temp_node.set_info("changedname")
the "node_pre" parameter of temp_node shall be "PRE" as initialized, instead of being replaced by the Default parameter in the function "set_info", i.e.
node_temp.node_pre != sign
the question is simple: how to implement it?
Thanks~
class DefaultNode(object):
def __init__(self, node_name, node_pre= None, node_next = None, act_func='sign', agg_func='sum', bias=0.0, response=1.0, node_type=None):
self.node_name = node_name
self.node_pre = node_pre
self.node_next = node_next
self.act_func_name = act_func
self.agg_func_name = agg_func
if act_func == "sign":
self.act_func = signmus_activation()
if agg_func == 'sum': # sign 和sum 是作为一个初始标记使用
self.agg_func = sum
self.bias = bias
self.response = response
self.node_type = node_type
def set_info(self, node_pre= None, node_next = None, act_func='sign', agg_func='sum', bias=0.0, response=1.0):
self.node_pre = node_pre
self.node_next = node_next
self.act_func_name = act_func
self.agg_func_name = agg_func
if act_func == "sign":
self.act_func = signmus_activation()
if agg_func == "sum":
self.agg_func = sum
self.bias = bias
self.response = response
EDIT 2: Updated my response after you clarified your question further (thanks!).
Option 1: You can use **kwargs and setattr to keep the parameter lists in sync. For example,
class Example(object):
def __init__(self):
self.first = 1
self.second = 2
def set_info(self, **kwargs):
for argument, value in kwargs.items():
if not hasattr(self, argument):
raise ValueError('invalid argument {}'.format(argument))
setattr(self, argument, value)
# Usage
e = Example()
print(e.first, e.second)
e.set_info(first=1000, second=2000)
print(e.first, e.second)
# This would raise an exception
# e.set_info(some_random_attribute='blah')
This outputs:
1 2
1000 2000
Option 2: Instead of having a separate method for setting fields, you could use #property and a corresponding setter for each. For example,
class Properties(object):
def __init__(self):
self._thing = 10
#property
def thing(self):
return self._thing
#thing.setter
def thing(self, t):
self._thing = t
# Usage
p = Properties()
print(p.thing)
p.thing = 20
print(p.thing)
Which prints
10
20
I'm getting a random ordered dict every time I compile, even using ordered dict. Im using dictionary to represent trees so its important to respect the order of the nodes. I had tried with python 3.6 and 3.7
class NP: #NounPhrase
def __init__(self, anchor = None, number = None):
self.anchor = anchor
self.number = number
class VP: #VerbPhrase
def __init__(self, anchor = None , person = None, tense = None):
self.person = person
self.tense = tense
self.anchor = anchor
class Tree:
def __init__(self, tree, sust = None, insert = None, anchor = None, terminal = None):
self.tree = tree
self.sust = sust
self.insert = insert
self.root = self.getRoot()
def getRoot(self):
return list(self.tree.keys())[0]
class TreeForest:
def makeIntransitiveVerb(text):
vp = VP(text)
return Tree( OrderedDict({ VP:{ NP , vp }}) )
verb = TreeForest.makeIntransitiveVerb("showed up")
print(verb.tree)
Expected result:
{< class '__main__.VP' > : { < class '__main__.NP' > , < __main__.VP object at 0x7f4b81fd8b90>}}
Actual results:
{< class '__main__.VP' >: {< __main__.VP object at 0x7f4b81fd8b90 >, < class '__main__.NP' >}})
Or
{< class '__main__.VP' >: { < class '__main__.NP' > , < __main__.VP object at 0x7f4b81fd8b90>}}