Class method.. Print the monthly interest amount. Python - 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.)

Related

AttributeError: class object has no attribute

I am new to python. I try to access the attribute acnt_amount from the class bank_Customer, but throws "AttributeError" error. How to access the attribute of the function getDetails to withdraw with in the class from one function to another function? What is the mistake that i do? Any help will be much appreciated! Thanks in advance!
Code:
class bank_Customer:
def getDetails(self, cname, acnt_no, acnt_type, acnt_amount):
self.cname = cname
self.acnt_no = acnt_no
self.acnt_type = acnt_type
self.acnt_amount = acnt_amount
row = self.cname + "," + str(self.acnt_no) + "," + self.acnt_type + "," + str(self.acnt_amount) + "\n"
file = open('cust_details.csv','a')
file.write(str(row))
file.close()
print('*'*40)
print("Account has been added successfully!")
return self.acnt_amount
def withdraw(self):
cash = int(input("Please enter the amount to be withdrawn: "))
self.acnt_amount = self.acnt_amount - cash
f"balance amount is {balance}"
return balance
base = bank_Customer()
base.withdraw()
Error:
Traceback (most recent call last):
File "C:\Users\kisha\IdeaProjects\Git projects in python\ATM application.py", line 96, in <module>
base.withdraw()
File "C:\Users\kisha\IdeaProjects\Git projects in python\ATM application.py", line 66, in withdraw
self.acnt_amount = self.acnt_amount - cash
AttributeError: 'bank_Customer' object has no attribute 'acnt_amount'
As suggested, an init is required. Also consider setting up some defaults, and look at the use of "getters and setters".
You may gain some insight from the following sample bank account class that I wrote some time ago as an example.
# #Author:srattigan
# #Date:2020-12-10 11:10:33
# #LastModifiedBy:srattigan
# #Last Modified time:2020-12-14 09:50:13
# demo class for inheritance
class BankAccount:
"""Generic Bank Account
"""
acc_num = 100000
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.account_num = self.acc_num
BankAccount.acc_num += 1
def deposit(self, amount):
assert amount > 0, ValueError("Must deposit a positive amount")
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def __str__(self):
rep = f"Bankaccount for {self.name}"
rep += f"\n\tAcc Num: {self.account_num}"
rep += f"\n\tBalance: €{self.balance:.2f}"
return rep
customer = BankAccount("Fred Jones", 99)
print(customer)
You need to def init as your first method. Thats where you specify cname, acnt_no etc.
you need to declare the variables inside the class first.
create the init() constructor to declare and initialize those variables

Python class define not being recognized

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

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

How to calculate variable declared in a method from inside python class function

need help about my code (python):
class Account:
def __init__(self, money):
self.money= money
def __str__(self):
return f'Money in the bank: {self.money} dollar'
def withdraw(self,withdraw):
self.withdraw = withdraw
money = self.money-self.withdraw
return money
print(Account.withdraw(20000,1000))
What I want from code above is the code will print my remaining money (19000), but I always got error
'int' object has no attribute 'withdraw'.
I have tried a lot of things for 4 hours but got no satifying result.
This is my first question in this forum, i am sorry if the formatting is not right.
Thank you in advance :)
Below I have made some small changes in your code and it is working as you expect.
Defined new variable withdrawMoney to track the withdraw amount.
Some changes in string format.
Returned the updated amount every time.
class Account:
def __init__(self, money):
self.money= money
self.withdrawMoney = 0
def __str__(self):
return "Money in the bank: {} dollar".format(self.money)
def withdraw(self,withdrawMoney):
self.withdrawMoney = withdrawMoney
self.money = self.money-self.withdrawMoney
return self.money
acc = Account(20000)
print(acc.withdraw(1000)) # 19000
print(acc.withdraw(1000)) # 18000

Errors in minor details in a class output

I have two files :
class Account:
def __init__(self,id=0,balance=100.0,AIR=0.0):
self.__id = id
self.__balance = balance
self.__AIR = AIR
def getd(self):
return self.__id
def getbalance(self):
return self.__balance
def getAnnualInterest(self):
return self.__AIR
def setid(self,newid):
self.__id = newid
def setbalance(self,newbalance):
self.__balance = newbalance
def setAnnualInterestRate(self,newrate):
self.__AIR = newrate
def getMonthlyInterestRate(self):
return self.__AIR/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.setid} Account Balance : {0.setbalance} Annual Interest Rate : {0.setAnnualInterestRate}".format(self)
and Test:
from Account import Account
def main():
accountA = Account(0,100,0)
accountA.setid = 1234
accountA.setbalance = 20500
accountA.setAnnualInterestRate = 0.375
print(accountA)
accountA.withdraw(500)
accountA.deposit(1500)
print(accountA)
print(accountA.getMonthlyInterest())
main()
My output is mostly correct but there are two minor deatils which I have gotten wrong and I am not sure where in the code the problem is from.
Account ID : 1234 Account Balance : 20500 Annual Interest Rate : 0.375
Account ID : 1234 Account Balance : 20500(This is supposed to be 21500) Annual Interest Rate : 0.375
0.0(And this is supposed to be 671.875 but somehow I got it wrong)
accountA.setbalance = 20500 doesn't call the setbalance method. It changes the value of the setbalance attribute to 20500 (that is, after this line, accountA.setbalance is no longer a method but an int). Instead, you want accountA.setbalance(20500).
However, what you're doing is profoundly un-pythonic in the first place (you're a Java/C#/C++ programmer, aren't you?). Getters and setters are an anti-pattern in Python: just access and change the id, balance et al. attributes, and make them properties if (and only if) you need to perform computations/checks when setting/accessing them.
In addition, __attribute is not a private attribute in Python. The pythonic way to mark an attribute as "private" is a single leading underscore. However, it's just a convention, and the attribute itself will still be public (everything always is in Python -- it has no concept of visibility modifiers).
This:
accountA.setid = 1234
accountA.setbalance = 20500
accountA.setAnnualInterestRate = 0.375
doesn't call the functions. You actually change functions into variables this way. To call the functions use this notation:
accountA.setid(1234)
accountA.setbalance(20500)
accountA.setAnnualInterestRate(0.375)

Categories