Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7代码没有给出正确答案_Python - Fatal编程技术网

Python 2.7代码没有给出正确答案

Python 2.7代码没有给出正确答案,python,Python,出于某种原因,代码似乎没有从正确的对象中扣除,而只是在我的代码中添加到接收者,我如何解决这个问题,以便接收者将正确的金额添加到他的余额中 class BankAccount: def __init__(self, balance): self.balance = balance self.tamout = 0 def withdraw(self, amount): self.balance -= amount r

出于某种原因,代码似乎没有从正确的对象中扣除,而只是在我的代码中添加到接收者,我如何解决这个问题,以便接收者将正确的金额添加到他的余额中

class BankAccount:
    def __init__(self, balance):
        self.balance = balance
        self.tamout = 0


    def withdraw(self, amount):
        self.balance -= amount
        return self.balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

    def transfer(self, name, c):
        self.balance -= c
        name += c
        return name

David = BankAccount(400)
John = BankAccount(200)

print "David balance is", David.balance
print "john balance is", John.balance

John.transfer(David.balance, 20)

print John.balance
print David.balance   
结果是

David balance is 400
john balance is 200

180

400

最后一次打印不应该是420吗?

您当前的传输函数接收的是接收者余额的副本,而不是原始属性

请尝试以下方法:

def传输(自身、名称、c): 自平衡-=c name.balance+=c 返回名称
John.transfer(大卫,20岁)

这应该可以解决您的问题


class BankAccount:
    def __init__(self, balance):
        self.balance = balance
        self.tamout = 0


    def withdraw(self, amount):
        self.balance -= amount
        return self.balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

    def transfer(self, receiver, c):
        self.balance -= c
        receiver.deposit(c)
        return receiver

if __name__ == '__main__':

    David = BankAccount(400)
    John = BankAccount(200)

    print "David balance is", David.balance
    print "john balance is", John.balance

    John.transfer(David, 20)

    print John.balance
    print David.balance


通过使用David实例并在其上使用
存款
方法

John.transfer(David.balance,20)
您如何定义
.transfer()
?这就是问题所在。我可能很笨,但你不应该把整个Receiver实例都交给transfer函数,让它知道从aka
def transfer(self,receiver,c)中扣除谁:
然后
John.transfer(David,20)
感谢编辑格式化代码,但仍然无法找到如何格式化代码。repl.it/@aravindsuresh\u gh/EasygoingCooperativeMedia