Python新手问题 - 不打印正确的值

时间:2011-10-01 18:32:20

标签: python python-3.x

我是python的新手,我正在用Python做一些OOPS概念探索。

以下是我的帐户类:

class Account:
    def __init__(self,balance):
        self.__balance=int(balance)

    def deposit(self,deposit_amt):
        self.__balance=self.__balance + int(deposit_amt)

    def withdraw(self,withdraw_amt):
        withdraw_amt=int(withdraw_amt)
        self.__balance=self.__balance -- int(withdraw_amt)
        print(self.__balance)
        print("Subtracting" + str(withdraw_amt))

    def get___balance(self):
        return(self.__balance)

    def __str__(self):
        return("The Balance in the Account is " + str(self.get___balance()))

account_test计划:

import account
def main():
    balance_amt = input("Enter the balance amount \t")
    new_account=account.Account(int(balance_amt))


    deposit_amt=input("Enter the Deposit Amount \t")
    new_account.deposit(deposit_amt)
    print(new_account)

    withdraw_amt=input("Enter the Withdraw Amount \t")
    new_account.withdraw(withdraw_amt)
    print(new_account)


main()

但我得错了输出:

Enter the balance amount    3000
Enter the Deposit Amount    400
The Balance in the Account is 3400
Enter the Withdraw Amount   300
3700
Subtracting 300
The Balance in the Account is 3700

当我withdraw时,我收到的金额却减去了。我在这做错了什么?

由于我是新手,我在编程实践中需要一些建议。我的编码风格合适吗?

2 个答案:

答案 0 :(得分:2)

使用双--(负数),您将减去负值(即添加正值)。
更明确的解释如下:

self.__balance = self.__balance - (0 - int(withdraw_amt))

因此,改变这个:

self.__balance=self.__balance -- int(withdraw_amt)

对此:

self.__balance=self.__balance - int(withdraw_amt)

或者更好的是,对此:

self.__balance -= int(withdraw_amt)

答案 1 :(得分:1)

self.__balance=self.__balance -- int(withdraw_amt)

实际上被解析为

self.__balance=self.__balance - (- int(withdraw_amt))

也就是说,它正在添加提款金额。尝试使用单个-