Errors in minor details in a class output - python

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)

Related

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

OOP: How to write pythonic interaction between classes?

I would like to model the interaction between two classes where one of the classes takes the other one as an argument in one of its methods. Which class should be in the argument of the method of the other class?
I have written two alternative solutions to the problem but I am not sure which one of them is considered to be the correct way of handling this issue. Maybe there is even a better way but here are my two alternatives:
class BankAccount:
def __init__(self, balance):
self._balance = balance
def transaction(self, cash):
self._balance += cash._value
cash._value = 0
class Cash:
def __init__(self, value):
self._value = value
def transfer(self, bank_account):
bank_account._balance += self._value
self._value = 0
if __name__ == "__main__":
# First alternative
acc = BankAccount(balance=100)
cash = Cash(value=10)
print('-' * 30)
print('First alternative')
print(f'Account balance before: {acc._balance}')
print(f'Cash value before: {cash._value}')
acc.transaction(cash=cash)
print(f'Account balance after: {acc._balance}')
print(f'Cash value after: {cash._value}')
# Second alternative
acc = BankAccount(balance=100)
cash = Cash(value=10)
print('-' * 30)
print('Second alternative')
print(f'Account balance before: {acc._balance}')
print(f'Cash value before: {cash._value}')
cash.transfer(bank_account=acc)
print(f'Account balance after: {acc._balance}')
print(f'Cash value after: {cash._value}')
As you can see, both alternatives show the same results but I'd be happy to get a recommendation for the pythonic way of modelling this kind of class interaction. Thanks.
The example is ill-formed which prevents us from concentrating on actual OOP. It does not make sense for some cash to lose its value because it is tranfered. Does a $20 bill lose its value because you deposit it at the bank?
A new example
Instead let's consider the problem of representing money transfer between two bank accounts.
A key concept of OOP is that attributes of an instance should not be directly updated. Instead, the instance should provide an API via methods which provide some control over its state.
We can accomplish that by defining the methods deposit and withdraw for a BankAccount. This way, we can then define the method transfer_to which only makes use of this API.
class BankAccount:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount >= self.balance:
self.balance -= amount
else:
raise ValueError('Insufficient funds')
def transfer_to(self, target, amount):
if isinstance(target, BankAccount):
self.withdraw(amount)
target.deposit(amount)
else:
raise ValueError("'target' must be another BankAccount")
Advantage
By encapsulating the logic of withdraw, deposit and tranfer_to, we allow for simple implementation of more complex types of accounts through inheritance.
Here let's give the example of a new type of BankAccount which allows for negative balance.
class CreditAccount(BankAccount):
def withdraw(self, amount):
self._balance -= amount
By fully delegating the responsability of withdrawing to instances of BankAccount, we allow external agents to manipulate an account without having to be aware of the inner logic of withdrawing and depositing.

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.

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

An exercise from fundamentals of python [duplicate]

This question already exists:
Closed 11 years ago.
Possible Duplicate:
Fundamentals of Python Chapter 8 project 3
Hi I am a newbie programmer who just started to learn about python.
I have recently posted this same question before and I have solved it but my answer is not exactly what the question is asking.
I need help on why I need to implement a new method even though I could do the other way.
thanks
Question:
The __str__ method of the Bank class returns a string containing the
accounts in random order. Design and implement a change that causes
the accounts to be placed in the string by order of name.
[this is the part where I don't understand]
(Hint: You will also have to define a new method in the SavingsAccount class.)
class Bank(object):
def __init__(self):
self._accounts = {}
def __str__(self):
"""Return the string rep of the entire bank."""
pTemp =[]
for i in xrange(len(SavingsAccount.temp)-1):
if self._accounts.get(SavingsAccount.temp[i]).getName() >= self._accounts.get(SavingsAccount.temp[i+1]).getName():
temp = SavingsAccount.temp[i]
SavingsAccount.temp[i] = SavingsAccount.temp[i+1]
SavingsAccount.temp[i+1] = temp
for i in SavingsAccount.temp:
pTemp.append(self._accounts[i])
return '\n'.join(map(str, pTemp))
def add(self, account):
"""Inserts an account using its PIN as a key."""
self._accounts[account.getPin()] = account
def remove(self, pin):
return self._accounts.pop(pin, None)
def get(self, pin):
return self._accounts.get(pin, None)
def computeInterest(self):
"""Computes interest for each account and
returns the total."""
total = 0.0
for account in self._accounts.values():
total += account.computeInterest()
return total
class SavingsAccount(object):
"""This class represents a Savings account
with the owner's name, PIN, and balance."""
RATE = 0.02
temp = []
def __init__(self, name, pin, balance = 0.0):
self._name = name
self._pin = pin
self._balance = balance
SavingsAccount.temp.append(self)
def __str__(self):
result = 'Name: ' + self._name + '\n'
result += 'PIN: ' + self._pin + '\n'
result += 'Balance: ' + str(self._balance)
return result
def getBalance(self):
return self._balance
def getName(self):
return self._name
def getPin(self):
return self._pin
def deposit(self, amount):
"""Deposits the given amount and returns the
new balance."""
self._balance += amount
return self._balance
def withdraw(self, amount):
"""Withdraws the given amount.
Returns None if successful, or an
error message if unsuccessful."""
if amount < 0:
return 'Amount must be >= 0'
elif self._balance < amount:
return 'Insufficient funds'
else:
self._balance -= amount
return None
def computeInterest(self):
"""Computes, deposits, and returns the interest."""
interest = self._balance * SavingsAccount.RATE
self.deposit(interest)
def main():
bank = Bank()
bank.add(SavingsAccount("Zelda","1003",5000.00))
bank.add(SavingsAccount("Wilma","1001",4000.00))
bank.add(SavingsAccount("Fred","1002",1000.00))
print bank
main()
I think the question expects you to define ordering in the SavingsAccount class, that is, be able to determine whether an instance of SavingAccounts comes after or before another instance of SavingAccount. I don't want to write any spoiler here, but tell me if my hint is not enough ;).
UPDATE
Also, a common source of errors in Python with string ordering : a comes before z which comes before A which comes before Z ...
UPDATE2
more hints ;)
What you really want here is to sort a list of instances of SavingAccount according to a given criteria. There are 2 way to do this kind of thing. You can either :
have the one doing the sorting take care of it
or you can have the instances stored in your list taking care of it.
The second option is usually better because "the class to be sorted" should know better than anybody else how to sort itself (it's about encapsulation : not letting people outside control how your class works). Even though the question is not really clear, and the example is not very good (in my opinion), this is the option they would like you to chose.
The idea is that the Bank should just do something like this :
class Bank(object):
def __str__(self):
"""Return the string rep of the entire bank."""
#get a sorted copy of the list
#using default SavingAccount comparison
pTemp =sorted(self._accounts)
return '\n'.join(map(str, pTemp))
And SavingAccount contains information about how to sort.
You may want to have a look at this article from the PythonInfo Wiki.
Also: http://docs.python.org/reference/datamodel.html#object.__lt__

Categories