【发布时间】:2019-11-16 21:06:37
【问题描述】:
我一直致力于改进在 Python 中使用类和对象,但在我的程序中显示不同对象的值时遇到了麻烦。我的导师告诉我,只要将对象传递给 print() 函数,就会自动调用 str(self) 函数,但是,输出仍然显示对象在内存中的地址,而不是价值。我在下面记录了我的代码在两个不同的编译程序中运行它,但仍然找不到我的错误发生的位置。
# the class of the bank account
class BankAccount:
def __init__(self, bal):
self.__balance = bal
# deposits the amount given by the user
def deposit(self, amount):
self.__balance += amount
# withdraws the amount given by the user
def withdraw(self, amount):
if(self.__balance >= amount):
self.__balance -= amount
else:
print("Error: Insufficient funds")
# returns the current balance of the user's account
def get_balance(self):
return self.__balance
# sets the user's account given a specified balance
def set_balance(self, bal):
self.__balance = bal
# prints the user's balance
def __str__(self):
return "The balance is $" + format(self.__balance, ",.2f")
def main():
start_bal = float(input("Enter your starting balance: ")) # retrieves balance from the user
savings = BankAccount(start_bal) # creates an object that hold's the user's balance
print(savings)
main()
程序输出<__main__.BankAccount object at 0x0000025EE6535A90>而不是获取帐户的值
请让我知道我可以更改以纠正问题的任何内容。谢谢。
【问题讨论】:
-
你的格式有问题,需要缩进defs
-
这些函数不在类中,只有
__init__在你的类中,你应该正确格式化你的代码 -
谢谢大家都是正确的!但是,我有一个问题。你知道为什么函数需要在类中缩进吗?为什么程序中已经声明了它们,我却无法正确使用它们?
标签: python string class object printing