【问题标题】:Python Newbie Questions - Not printing correct valuesPython新手问题 - 不打印正确的值
【发布时间】:2011-10-01 18:32:19
【问题描述】:

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

以下是我的 Account 类:

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 时,我得到的是加法而不是减法。我在这里做错了什么?

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

【问题讨论】:

  • 在编码风格上,不要使用双下划线来平衡——就叫它self.balance。而且没有理由定义get_balance 方法。 Python的做法是直接访问属性。
  • 感谢丹尼尔的回复。但是我正在阅读的是,如果您想将您的变量设为私有,您需要在变量前面添加 __,以便 python 将其视为该类的私有变量。如果我错了,请纠正我。如果不是如何在 python 中声明一个私有变量。我知道默认情况下python不会让你,但转身是添加__。
  • Python 中没有私有变量。 __ 只是进行名称修改,很难找到。

标签: python python-3.x


【解决方案1】:

使用双精度 --(负),您减去一个负值(即添加一个正值)。
更清晰的解释如下:

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)

【讨论】:

    【解决方案2】:
    self.__balance=self.__balance -- int(withdraw_amt)
    

    实际上被解析为

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

    也就是说,是增加提现金额。尝试使用单个 -

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-25
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2021-04-29
      • 1970-01-01
      • 2022-07-11
      相关资源
      最近更新 更多