Python class define not being recognized - python

Ok, so I've been trying to create a Python 3.9 program that's designed to ask the user for the sales amount for the month, and call the "county" and "state" functions, to find the taxes collected on it. I've been reading up on functions, classes, and whatnot but I can't seem to figure out what I'm doing wrong. It's supposed to have the program tell the total sales tax collected at the end of the program. (So if 100000 was entered by the user, the total tax collected would be 7750 for that month.) But everything I do leads to a brick wall, as of now I'm getting: "name 'main' is not defined"
This feels like one of those issues that takes like 3 seconds to fix but I just can't seem to pinpoint the issue. None of the online tutorials or other questions have really helped me either. Any thoughts?
class Tax:
#combined sales
def sales_combined():
county_sales_number() + state_sales_number()
#main
def main():
sales_Amount = int(input("What was the sale amount for the month? "))
print("The total sales tax collected is " + sales_combined())
#county sales division
def county_tax():
countyValue = 0.015
#state sales division
def state_tax():
stateValue = 0.0625
#county sales
def county_sales_number():
sales_Amount / county_tax()
#state sales
def state_sales_number():
sales_Amount / state_tax()
main()

I think you came from a Java background. In your snippet, main is a function inside of Tax, so if you want to access it, you need to do
class Tax:
...
Tax.main()
However, this will raise an AttributeError, since sales_combined is not defined. To be able to access it, you need to make main an instance method of Tax:
class Tax:
...
def main(self):
...
# Access the method using `self`
self.sales_combined()
tax = Tax()
tax.main()
An alternative (and recommended) approach is to make it a function, so you would separate your business logic from your driver code:
def main():
tax = Tax()
sales_Amount = int(input("What was the sale amount for the month? "))
print("The total sales tax collected is " + tax.sales_combined())
class Tax:
...
main()

Related

How to change variable value from another class?

So I am working on a project which basically is to program a Monopoly. I want to be able for a player to pay X amount to the bank and have the bank properly receive and add that amount to its own. I am working the player on a Tkinter interface in a different class to the bank. I have done the following:
In Class Card1, import the Bank class from bank.py
Program a function pay_bank() where I get the amount entered in the Entry field and discount it from the player's available money and send it to bank.
-Create a function receive_payment() in the Bank class where it receives the player's money and adds it to its own.
For some reason, it is not working so I need your help. Code below:
Class Card1:
def __init__(self):
self.amount = 1500
self.properties = {}
#nested functions to handle interface and it's events
def manage_player1_card(self):
def pay_bank():
to_bank = int(payBox.get())
if self.amount > to_bank:
payBox.delete(0, END)
self.amount -= to_bank
Bank().receive_payment(to_bank)
class Bank:
def __init__(self):
self.bank_total = 14580
def receive_payment(self, pay):
self.bank_total += pay
*Indentation might look wrong due to copy-pasting but it is just fine in my code. What do you see I am doing wrong?
Basically, the self.bank_total amount is not adding up every time I enter the amount. For example: if I enter 500, it should go up to 15180, but it stays the same at 14580. I have debugged but it doesn't change. How can I fix this? Thanks!
Try something like this:
def pay_bank(bank: Bank):
...
bank.receive_payment(to bank)
That way you are passing the bank as a parameter.

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

TypeError: unorderable types: atm() >= int()

I have 3 classes, ATM (main class), atmFees (subclass of ATM) and transaction. I want to have my class atmFees inherit methods from the parent class ATM.
The atmFees class takes the atm object as a parameter, initializing with atm.__init__(self, balance)
I want to override the parent/super class's "withdrawal" method, modifying one of the parameters -- subtracting 50 cents from amount -- and then accessing the super method in atm with the new amount.
Doing so returns a TypeError: unorderable types: atm() >= int()
I have absolutely no idea what to do from here, I've changed almost everything but I can't seem to get it to work.
import transaction
import random
class atm(object):
def __init__(self, bal):
self.__balance = bal
self.transactionList = []
def deposit(self, name, amount):
self.__balance += amount
ndt = transaction.Transaction(name, amount)
self.transactionList.append(ndt)
def withdraw(self, name, amount):
if self.__balance >= amount:
self.__balance -= amount
nwt = transaction.Transaction(name, amount)
self.transactionList.append(nwt)
else:
print('Uh oh, not enough money!')
def get_balance(self):
return self.__balance
def __str__(self):
string_return = ""
for transaction in self.transactionList:
string_return += str(transaction) + "\n"
string_return = '\n' + 'The balance is $' + format(self.__balance, ',.2f')
return string_return
class atmFee(atm):
def __init__(self, balance):
atm.__init__(self, balance)
def widthrawal(cls, name, amount):
amount = amount - .50
atm.widthrawal(cls, name, amount)
def deposit():
pass
def main():
myATM = atm.atm(75)
fees = atm.atmFee(myATM)
fees.withdraw("2250",30)
fees.withdraw("1000",20)
myATM.deposit("3035",10)
print("Let's withdraw $40")
if myATM.withdraw("Amazon Prime",40) == 0:
print ("Oh noes! No more money!")
print()
print("Audit Trail:")
print(myATM)
main();
The full code is posted here:
https://gist.github.com/markbratanov/e2bd662d7ff83ca5ef61
Any guidance / help would be appreciated.
The error message means just what it says - you can't order an object and an integer. This is possible (for some reason) in Python 2, where the ordering is essentially arbitrary (for example, an empty dict {} is always greater than an integer, no matter how large...), but it is not in Python 3, because the comparison is meaningless.
You create your ATM object like this:
myATM = atm.atm(75)
fees = atm.atmFee(myATM)
So myATM, itself an ATM object, gets passed in to atmFee.__init__ as the balance. In withdraw, you expect the balance to be a number and not an ATM object (if the comparison worked, the arithmetic you do on it would then fail). You almost certainly meant to set the balance to a number by creating the object like this:
fees = atm.atmFee(75)
Note that atmFee takes exactly the same constructor signature as the superclass (this isn't a rule, but it is how you've set it up here), so you should use it in the same way.
You are also switching between using fees and myATM in the rest of your code, which seems odd. It looks like you mean to be using fees in all cases, and don't actually need myATM at all.

Python: Class and SubClass - Why won't in recognize the subclass

I am trying to create a class that contains the salary and bonus attributes and another that contains the name and idnum attributes. With a small program that asks if the shift has met goal for the year and then figures the total income for the shift supervisor for the year. Every time I try I get:
File "C:\Python33\12-2.py", line 53, in main
shift1 = Shiftsupervisor.Employee('28000.0','2240.0','Ian McGregor', 'S10001' )
AttributeError: type object 'Shiftsupervisor' has no attribute 'Employee'
What have I done wrong??
# This creates two classes - ShiftSupervisor & Employee
# The program then tells us what the annual income is
# This creates a class of Super Class Shiftsupervisor which contains salary, & bonus \
figures
class Shiftsupervisor:
#Initialize the Shiftsupervisor attributes
def __init__(self, salary, bonus):
self.__salary = salary
self.__bonus = bonus
# creates the mutator for the attributes
def set_salary(self, salary):
self.__salary = salary
def set_bonus(self, bonus):
self.__bonus = bonus
# returns the attributes
def get_salary(self):
return self.__salary
def get_bonus(self):
return self.__bonus
#Create the subclass of employee which holds the name & idnum
#Initialize the employee attributes
class Employee(Shiftsupervisor):
def __init__(self, salary, bonus, name, idnum):
Shiftsupervisor.__init__(self, salary, bonus)
#Initialize the employee new attributes
self.__name = name
self.__idnum = idnum
#creates the new mutator for name & id
def set_name(self, name):
self.__name = name
def set_idnum(self, idnum):
self.__idnum = idnum
# new method returns the name & id
def get_name(self):
return self.__name
def get_idnum(self):
return self.__idnum
#This program take info from the two classes and gives
# the total income for the Shift Supervisor
#Creates the shift supervisor objects
def main():
shift1 = Shiftsupervisor.Employee('28000.0','2240.0','Ian McGregor', 'S10001' )
shift2 = Shiftsupervisor.Employee('29500','2360.0','Brian Bory', 'S20202' )
shift3 = Shiftsupervisor.Employee('28750.0','2300.0''Finn McCool', 'S30045' )
def total_income():
if production == 'y' or 'Y':
return __salary + __bonus
else:
return __salary
#Ask the Question - Did they make production quota
production = input('Did Shift 1 make quota this year? Type Y for yes ' )
#Print the income
print(shift1.get_name(),'s Total income is: $', format(total_income, \
',.2f'), sep='')
#Ask the Question - Did they make production quota
production = input('Did Shift 2 make quota this year? Type Y for yes ' )
#Print the income
print(shift2.get_name(),'s Total income is: $', format(total_income, \
',.2f'), sep='')
#Ask the Question - Did they make production quota
production = input('Did Shift 3 make quota this year? Type Y for yes ' )
#Print the income
print(super3.get_name(),'s Total income is: $', format(total_income, \
',.2f'), sep='')
#call the main function
main()
Your code has the following problems:
I think it'd be better have ShiftSupervisor be a subclass of Employee. Unless I'm misunderstanding, a shift supervisor is a kind of employee, so employee is the base class. A shift supervisor might have additional attributes that specialize the Employee class. I've added the shift_number attribute to demonstrate this.
Your main method only creates the employees, but doesn't ever do anything with them.
Your total_income method is a bit confused. Remember, __salary and __bonus are attributes of an object. You have do always use the form instance.attribute in order to get access to those.
You don't need getters and setters in Python. The convention is to keep them normal fields that are meant to be publicly accessible, and use properties if it turns out you do need more complex accessing logic.
The salary and bonus shouldn't be a string -- they're numeric values.
Taken together, your new code might look something like this:
class Employee:
def __init__(self, salary, bonus, name, idnum):
self.salary = salary
self.bonus = bonus
self.name = name
self.idnum = idnum
class ShiftSupervisor(Employee):
def __init__(self, salary, bonus, name, idnum, shift_number):
super().__init__(salary, bonus, name, idnum)
self.shift_number = shift_number
def main():
shift1 = ShiftSupervisor(28000.0, 2240.0, 'Ian McGregor', 'S10001', 1)
shift2 = ShiftSupervisor(29500, 2360.0, 'Brian Bory', 'S20202', 2)
shift3 = ShiftSupervisor(28750.0, 2300.0, 'Finn McCool', 'S30045', 3)
find_income(shift1)
find_income(shift2)
find_income(shift3)
def find_income(employee):
production = input('Did shift {0} make quota this year? Type Y for yes '.format(employee.shift_number))
if production.lower() == 'y':
total_income = employee.salary + employee.bonus
else:
total_income = employee.salary
print("{0}'s Total income is: ${1}".format(employee.name, total_income))
main()
I'm also getting the feeling that you're entangling a shift and an employee in some way that you shouldn't be, though I'm quite able to put my finger on it. A shift might have more than one employee, and an employee could work multiple shifts, though this'll definitely depend based on what problem you're trying to solve.

Class method.. Print the monthly interest amount. Python

I am making a program that uses the class Account to print the monthly interest amount of accountA, among other things. I am having problems with getting the getMonthlyInterestRate() and getMonthlyInterest definitions to work out. Here is the program thus far:
Account.py
class Account:
def __init__(self,id=0,balance=100.0,annualInterestRate=0.0):
self.__id=id
self.__balance=balance
self.__annualInterestRate=annualInterestRate
def getId(self):
return self.__id
def getBalance(self):
return self.__balance
def getAnnualInterest(self):
return self.__annualInterestRate
def setId(self,newid):
self.__id=newid
def setBalance(self,newbalance):
self.__balance=newbalance
def setAnnualInterestRate(self,newannualInterestRate):
self.__annualInterestRate=newannualInterestRate
def getMonthlyInterestRate(self,getAnnualInterest):
return(getAnnualInterest(self)/12)
def getMonthlyInterest(self,getBalance,getMonthly):
return(getBalance(self)*getMonthlyInterestRate(self))
def withdraw(self,amount):
if(amount<=self.__balance):
self.__balance=self.__balance-amount
def deposit(self,amount):
self.__balance=self.__balance+amount
def __str__(self):
return "Account ID : "+str(self.__id)+" Account Balance : "+str(self.__balance)+" Annual Interest Rate : "+str(self.__annualInterestRate)
next
file test.py
from Account import Account
def main():
accountA=Account(0,100,0)
accountA.setId(1234)
accountA.setBalance(20500)
accountA.setAnnualInterestRate(0.375)
print(accountA.__str__())
accountA.withdraw(500)
accountA.deposit(1500)
print(accountA.__str__())
print(accountA.getMonthlyInterest(accountA.getBalance(),accountA.getAnnualInterest()))
main()
I cannot figure out how to make the getMonthlyInterestRate() and getMonthlyInterest() defintions to work out to be able to put out the right output, which is:
Account ID : 1234 Account Balance : 20500 Annual Interest Rate : 0.375
Account ID : 1234 Account Balance : 21500 Annual Interest Rate : 0.375
Monthly Interest Amount : 671.875
mine always comes out with the error statement:
Account ID : 1234 Account Balance : 20500 Annual Interest Rate : 0.375
Account ID : 1234 Account Balance : 21500 Annual Interest Rate : 0.375
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 13, in <module>
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 12, in main
File "C:\Users\Meagan\Documents\University\2nd Year\Cmput 174\Account.py", line 21, in getMonthlyInterest
return(getBalance(self)*getMonthlyInterestRate(self))
builtins.TypeError: 'int' object is not callable
this is what i should make:
a method named getMonthlyInterestRate() that returns the monthly interest rate.
a method named getMonthlyInterest() that return the monthly interest amount. The monthly interest amount can be calculated by using balance * monthly interest rate. The monthly interest rate can be computed by dividing the annual interest rate by 12.
everything else in the program is correct except for those two definitions and the last print statement. Any help would be appreciated. Thanks.
You should call methods on self, not by passing the functions around:
def getMonthlyInterest(self):
return self.getBalance() * self.getMonthlyInterestRate()
and call it with:
print(accountA.getMonthlyInterest())
This goes for getMonthlyInterestRate as well:
def getMonthlyInterestRate(self):
return self.getAnnualInterest() / 12
You use a lot of getters and setters; there is no need for these in Python; you don't need to make the attributes private, just access them directly instead:
class Account:
def __init__(self, id=0, balance=100.0, annualInterestRate=0.0):
self.id = id
self.balance = balance
self.annualInterestRate = annualInterestRate
def getMonthlyInterestRate(self):
return self.annualInterestRate / 12
def getMonthlyInterest(self):
return self.balance * self.getMonthlyInterestRate()
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
def deposit(self, amount):
self.balance += amount
def __str__(self):
return "Account ID : {0.id} Account Ballance : {0.balance} Annual Interest Rate : {0.annualInterestRate}".format(self)
then run:
def main():
accountA = Account(0,100,0)
accountA.id = 1234
accountA.balance = 20500
accountA.annualInterestRate = 0.375
print(accountA)
accountA.withdraw(500)
accountA.deposit(1500)
print(accountA)
print(accountA.getMonthlyInterest())
Result:
Account ID : 1234 Account Ballance : 20500 Annual Interest Rate : 0.375
Account ID : 1234 Account Ballance : 21500 Annual Interest Rate : 0.375
671.875
You define
def getMonthlyInterestRate(self,getAnnualInterest):
return(getAnnualInterest(self)/12)
def getMonthlyInterest(self,getBalance,getMonthly):
return(getBalance(self)*getMonthlyInterestRate(self))
and use them as
print(accountA.getMonthlyInterest(accountA.getBalance(),accountA.getAnnualInterest()))
in other words, you call them with the return values of the said functions, not with the functions themselves. Inside these functions, you try to call them again. As you didn't pass functions, but values, this "calling again" fails.
If you fix this bug, you (probably) make your program work, but youget a program written in very bad style.
To improve that, follow Martijn Pieters's hint.
(This answer should probably have been a comment, but these cannot be formatted nicely.)

Categories