[英]Why can't I change an instance variable from another object
Hi I actually found my solution to my problem.嗨,我实际上找到了解决问题的方法。 However, i just wanna know why can't I change an object instance variable(bye.balance) through another object's instance method(hello.deposit).但是,我只想知道为什么我不能通过另一个对象的实例方法(hello.deposit)更改 object 实例变量(bye.balance)。 Instead, I must invoke another instance method through another object instance method.相反,我必须通过另一个 object 实例方法调用另一个实例方法。 I wanna ask all programming gods here if is there any other method.我想问问这里所有的编程大神是否还有其他方法。
Problem: Basically if I change bye.balance through hello.deposit, bye.balance remain 0.问题:基本上如果我通过 hello.deposit 更改 bye.balance,bye.balance 保持为 0。
class People(object):
def __init__(self, name , cash, count):
self.cash=cash
self.name=name
self.count=count
def __str__(self):
rep=str(self.count) + '\t'+ self.name
return rep
def deposit(self, dep_amount, account):
self.cash-=dep_amount
bye.balance+=dep_amount
class Account(object):
def __init__(self, name, count, balance=0):
self.name=name
self.count=count
self.balance=balance
def __str__(self):
rep=str(self.count)+'\t'+'account by '+self.name
return rep
##def add(self, dep):
##self.balance+=dep
hello=People('cz', 1000, 0)
bye=Account('cz', 0)
dep=int(input('dep amount enter pls'))
hello.deposit(dep, bye.balance)
print(hello.cash, bye.balance)
hello.cash=12345
print(hello.cash)
I think you meant:我想你的意思是:
hello.deposit(dep, bye)
and the deposit method could be:存款方式可以是:
def deposit(self, dep_amount, account):
self.cash -= dep_amount
account.balance += dep_amount
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.