【发布时间】:2019-01-13 20:03:21
【问题描述】:
所以,我正在 python 中创建一个 Account 类。它具有存款、取款和查看余额的基本功能。不过,我在传输方法上遇到了麻烦。 这是我的代码(抱歉代码转储):
class Account:
"""simple account balance of bank"""
def __init__ (self, name, balance):
self.name = name
self.balance = balance
print('Account of ' + self.name)
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.statement()
def withdrawal(self, amount):
if amount > 0 and self.balance > amount:
self.balance -= amount
self.statement()
else:
print("the ammount in your is not sufficent")
self.statement()
def statement(self):
print("Hi {} your current balance is {}".format(self.name,self.balance))
def transfer(self, amount, name):
self.balance = self.balance - amount
name.balance = name.balance + amount
return name.balance()
现在,它适用于
abc = Account("abc", 0)
abc.deposit(1000)
siddharth = Account("siddharth", 159)
那么我该如何运行以下代码:
siddharth.transfer(11, "abc")
siddharth.transfer(11, Account.abc)
另外,如果帐户“abc”不存在,我如何创建帐户“abc”
【问题讨论】:
-
问题是你写的转移方法期望
name是一个Account对象(你正在调用name.balance)而name实际上是一个str("abc") -
显示我应该如何定义传递函数,我希望函数将金额传递给同一类的另一个对象
-
谢谢,@PatrickArtner 但解释器说“”TypeError: 'int' object is not callable"' 我希望能够使用帐户名称,而不是我给它的名称,如果这样的话感觉?所以我想说 Siddharth 已将 11 转移到帐户 abc siddharth.transfer(11,abc) 我只是不知道该怎么做。
-
一种方法是有一个查找功能,在转移之前首先找到帐户对象。找到对象后,可以在 transfer() 方法中传递它。如果没有找到,您可以创建一个对象并将其传递给 siddarth.transfer()
-
siddharth.transfer(11, abc)
标签: python python-3.x class oop object