我是Python新手,我在Python中做一些OOPS概念探索。Python新手问题 - 不打印正确的值
以下是我的帐号等级:
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中声明一个变量private。我知道默认python不会让你,但转过身来添加__。 – techrawther
Python中没有私有变量。 '__'仅仅是名字的混乱,使他们很难找到。 –