Python Call Parent Method from child method - python

I want to call the Method SavingsAccount.withdraw(600) but every time I get an exception TypeError: withdraw takes exactly 1 arguement(2 given). How do I fix this? Please advise.
class BankAccount(object):
def __init__(self):
pass
def withdraw(self):
pass
def deposit(self):
pass
class SavingsAccount(BankAccount):
def __init__(self):
self.balance = 500
def deposit(self, amount):
if (amount < 0):
return "Invalid deposit amount"
else:
self.balance += amount
return self.balance
def withdraw(self, amount):
if ((self.balance - amount) > 0) and ((self.balance - amount) < 500):
return "Cannot withdraw beyond the minimum account balance"
elif (self.balance - amount) < 0:
return "Cannot withdraw beyond the current account balance"
elif amount < 0:
return "Invalid withdraw amount"
else:
self.balance -= amount
return self.balance
class CurrentAccount(BankAccount):
def __init__(self, balance=0):
super(CurrentAccount, self).__init__()
def deposit(self, amount):
return super(CurrentAccount, self).deposit(amount)
def withdraw(self, amount):
return super(CurrentAccount, self).withdraw(amount)
x = CurrentAccount();
print x.withdraw(600)

The withdraw method in BankAccount is missing the amount:
class BankAccount(object):
def __init__(self):
pass
def withdraw(self): # <--- ADD THE AMOUNT HERE
pass
Same with the deposit method

Related

Cant finish a code, __init__() takes from 1 to 2 positional arguments but 3 were given

Hello i want to write a test program that creates an Account object with an account id of 1122, a balance of $20,000,and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit$3,000, and print the id, balance, monthly interest rate, and monthly interest but i keep getting
TypeError: __init__() takes from 1 to 2 positional arguments but 4 were given "
Here is how my code in file with class looks like
class Account:
def __init__(self,id=0,balance=20000,annualInterestRate=4.5):
self.__id = id
def getid(self):
return self.__id
def getbalance(self):
return self.__balance
def getannualInterestRate(self):
return self.__annualInterestRate
def setid(self,id):
self.__id = id
def setbalance(self, balance):
self.__balance = balance
def setannualInterestRate(self, rate):
self.__annualInterestRate = rate
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
return True
else:
return False
def deposit(self, amount):
self.__balance +=amount
return balance
and this is how i try to initialize it
from Acc import Account
def main():
updatedAccount = Account(1222,20000,4.5)
updatedAccount.withdraw(2500)
print("User ID : ", updatedAccount.getid())
print("Beginning Balance: ", updatedAccount.getbalance())
print("Monthly Interest Rate: ", updatedAccount.getMonthlyInterestRate())
print("Monthly Interest: ", updatedAccount.getMonthlyInterest())
main()
Can someone please help with the last part of a code where i try to initialize it
Just a thought, why don't you initialize the balance and interest in the init() body?
Then use the setbalance or setters to set the values when the user wants to change the initial value?
Answer to your question: You provided the values to the constructor as positional arguments. Whenever you use the keyword(kwargs) argument construct, remember to explicitly set them in the function call.
Example:
def do_some(i=34, j=23):
Function call:
do_some(i=23,i=12)
This is how your definition of Account should look:
class Account:
# No need for a default id; it should be required
# 0 is a better default for balance; banks don't give you $20,000 unless you specify otherwise :)
def __init__(self, id, initial_balance=0, rate=4.5):
self.id = id
self.balance = initial_balance
self.annual_interest_rate = rate
# Ditch the unnecessary getters and setters
# Example of a "computed attribute value", rather than an explicit method
#property
def monthly_interest_rate(self):
return self.annual_interest_rate / 12
def get_monthly_interest(self):
return self.balance * self.monthly_interest_rate
# Don't return True/False. Do the debit, or raise an exception
def withdraw(self, amount):
if self.balance < amount:
raise ValueError(f"Overdraft, balance less than {amount}")
self.balance -= amount
# Don't return the balance; mutating methods should return None.
# The caller can always check self.balance after the deposit
def deposit(self, amount):
self.balance +=amount
Example usage:
from Acc import Account
def main():
updatedAccount = Account(1222,20000,4.5)
updatedAccount.withdraw(2500)
print("User ID : ", updatedAccount.id)
print("Beginning Balance: ", updatedAccount.balance)
print("Monthly Interest Rate: ", updatedAccount.monthly_interest_rate)
print("Monthly Interest: ", updatedAccount.get_monthly_interest())
main()

Inheritance and Printing in Bank account in python

This is a section from my bank account code, i am new to OOP and have added some inheritance to my code, the trouble i am having is with printing the balance with interest, when i print it I get the same value as the regular balance without interest, give your insight.
from random import randint
class BankAccount(object):
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def get_balance(self, initial_balance, rate):
return self.get_balance() * self._rate
class BankAccountWithInterest(BankAccount):
def __init__(self, initial_balance=0, rate=0.1):
BankAccount.__init__(self, initial_balance)
self._rate = rate
def interest(self):
return self.balance * self._rate
balance = (randint(100, 500))
my_account = BankAccount(balance)
my_interest = BankAccountWithInterest(balance)
print(my_account.balance)
print(my_interest.balance)
You have a couple of problems here, the main one being that you don't ever apply (call) the interest function, which is why you get the same balance for both. You should do:
print(my_account.balance)
print(my_interest.balance + my_interest.interest())
I would also recommend changing self._rate to rate in the get_balance method, otherwise you may get an error when you call get_balance and it tries to access self._rate. You should also have it return self.balance or self.balance + rate otherwise you are getting an infinite loop.
print(my_interest.balance + my_interest.interest())
Seems to return what you expect.
my_interest.balance = my_interest.balance + my_interest.interest()
print(my_interest.balance)
Will also update the balance with the added interest.

having trouble with this python code

i get this error and i have tried going through the posts available on stack flow i do not still get the solution. this is the code
class BankAccount:
def _init_(self,balance):
self.balance = balance
def deposit(self,amount):
self.balance += amount
return self.balance
def withdraw(self,amount):
if amount>self.balance:
print "invalid transaction"
else:
self.balance -= amount
return self.balance
class MinimumBalanceAcccount(BankAccount):
// this is the error i get: IndentationError: expected an indented block
Its IndentationError.
complete the class definition.
class BankAccount:
def _init_(self,balance):
self.balance = balance
def deposit(self,amount):
self.balance += amount
return self.balance
def withdraw(self,amount):
if amount>self.balance:
print "invalid transaction"
else:
self.balance -= amount
return self.balance
class MinimumBalanceAcccount(BankAccount):
def __init__(self):
print "working"

AttributeError in my python code 2

I have the following line of codes in python:
class BankAccount:
def __init__ (self,balance = 0):
self.balance = balance
def deposit(self, deposit_amount= 30):
self.deposit_amount=deposit_amount
balance += deposit_amount
return balance
def withdraw (self,withdraw_amount= 10):
if withdraw_amount > balance:
raise RuntimeError('Invalid Transaction')
balance -= withdraw_amount
return balance
class MinimumBalanceAccount(BankAccount):
def __init__(self,balance = 0):
self.balance = balance
c = BankAccount()
c.deposit(50)
it gives me this error:
AttributeError("BankAccount instance has no attribute 'deposit'"
If your indentation is actually as you posted it, then the deposit function is defined within the __init__ method. As such, it's not an attribute to the class, but a mere function available within the __init__ method. The following code is simply a copy of your code, but with indentation fixed:
class BankAccount:
def __init__(self,balance=0):
self.balance = balance
def deposit(self, deposit_amount=30):
self.deposit_amount=deposit_amount
self.balance += deposit_amount
return self.balance
def withdraw(self,withdraw_amount=10):
if withdraw_amount > self.balance:
raise RuntimeError('Invalid Transaction')
self.balance -= withdraw_amount
return self.balance
class MinimumBalanceAccount(BankAccount):
def __init__(self,balance = 0):
self.balance = balance
c = BankAccount()
c.deposit(50)
This code works for me, as it does when I replace c = BankAccount() with c = MinimumBalanceAccount()

Why does this class program not return the balance?

Question: Develop a class BankAccount that supports these methods:
__init__(): Initializes the bank account balance to the value of the input argument or to 0 if no input argument is given
withdraw(): Take an argument as an input and withdraws it from the balance
deposit(): Take an amount as an input and add it to the balance
balance(): Returns the balance on the account
class ValueErrorException (Exception):
pass
class BankAccount:
accounts = 0
def __init__ (self, bal = 0.0):
BankAccount.accounts += 1
self.accountNumber = str(BankAccount.accounts)
self.balance = bal
def withdraw(self, amount):
if self.balance - amount < 0:
raise ValueErrorException("Illegal balance")
else:
self.balance -= amount
def deposit (self, amount):
self.balance += amount
def balance(self, amount):
return amount
The balance definition should be like this:
def balance(self):
return self.balance
You may also want to consider changing the variable name from balance to accountBalance so it doesn't affect the definition that is named the same. Your new code would now be:
class ValueErrorException (Exception):
pass
class BankAccount:
accounts = 0
def __init__ (self, bal = 0.0):
BankAccount.accounts += 1
self.accountNumber = str(BankAccount.accounts)
self.accountBalance = bal
def withdraw(self, amount):
if self.accountBalance - amount < 0:
raise ValueErrorException("Illegal balance")
else:
self.accountBalance -= amount
def deposit (self, amount):
self.accountBalance += amount
def balance(self):
return self.accountBalance
return self.balance
access the classes instance variable, not a functional argument. no need to pass amount to a function just to return it

Categories

Resources