Brad Boisen
Brad Boisen

Reputation: 9

Calling a method that modifies the value of another

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

Answers (3)

Daniel Underwood
Daniel Underwood

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:

  1. 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.
  2. Your 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.
  3. Not really a problem, but you would probably want __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

Kevin Schellenberg
Kevin Schellenberg

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

calico_
calico_

Reputation: 1221

Methods should include self, try this:

def withdraw(self, withdrawn):
    self.balance -= withdrawn

Upvotes: 0

Related Questions