【发布时间】: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