简体   繁体   English

如何从python类函数内部计算方法中声明的变量

[英]How to calculate variable declared in a method from inside python class function

need help about my code (python):需要有关我的代码的帮助(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我从上面的代码中想要的是代码将打印我剩余的钱(19000),但我总是出错

'int' object has no attribute 'withdraw'. “int”对象没有“withdraw”属性。

I have tried a lot of things for 4 hours but got no satifying result.我已经尝试了 4 个小时的很多事情,但没有得到令人满意的结果。

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.定义了新的变量withdrawMoney 来跟踪提款金额。

  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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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