简体   繁体   中英

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.

  1. Defined new variable withdrawMoney to track the withdraw amount.

  2. Some changes in string format.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM