Reputation: 9
I'm creating an Account class as part of a Python lab assignment, and I'm not understanding the issue that's occurring. The constructor functions as it's meant to when I pass values to the other methods, but then I have to create a method called withdraw.
I've written it as it sounds like it should be, but I'm receiving an error which reads
TypeError: unsupported operand type(s) for -: 'Account' and 'int'
The code segment for the method I created is below:
def withdraw(balance,withdrawn):
self.__balance=balance-withdrawn
... and it's being called further below as follows:
acct1.withdraw(2500)
The exercise specifically asks to have this method, as well as a similar deposit method to be used. The best I can figure is that it's the setup of the method, rather than the way I'm calling it. Any help and pointers would be greatly appreciated. Also, I'm still learning, so I apologize if I'm misusing any terms!
Upvotes: 0
Views: 47
Reputation: 2271
You have a couple issues. I assume part of your code is like this:
class Account:
# Rest of class
def withdraw(balance, withdrawn):
self.__balance = balance - withdrawn
You have a few problems:
withdraw()
should take a parameter for class. This should be self
for a member method like you have here or cls
for a static method to actually access instance (or class) variables. This will be the first parameter for any class method. Your error is coming from the fact that balance
is interpreted as an Account
, which means balance - withdrawn
tries to subtract an int
from an Account
. Such behavior is possible to obtain by overloading the correct operators.Account
class has a __balance
field, which should be used rather than passing a balance to the function. You could pass a balance for a static method, but that wouldn't be of much use.__balance
to be accessible to inheritors, so you would use _balance
for what would be equivalent to a protected fields in other languages.You would end up with something like this:
class Account:
# Rest of class
def withdraw(self, withdrawn):
# Withdraw (could also be self._balance -= withdrawn)
self._balance = self._balance - withdrawn
Upvotes: 1
Reputation: 845
As this is a class method, the current instance of Account (self) is being passed as the first argument to your function (balance). TypeError is thrown because the withdraw function is attempting to subtract an Account object from an int.
Try this instead:
def withdraw(self, withdrawn)
self.__balance -= withdrawn
Upvotes: 0
Reputation: 1221
Methods should include self, try this:
def withdraw(self, withdrawn):
self.balance -= withdrawn
Upvotes: 0