繁体   English   中英

为什么我不能从另一个 object 更改实例变量

[英]Why can't I change an instance variable from another object

嗨,我实际上找到了解决问题的方法。 但是,我只想知道为什么我不能通过另一个对象的实例方法(hello.deposit)更改 object 实例变量(bye.balance)。 相反,我必须通过另一个 object 实例方法调用另一个实例方法。 我想问问这里所有的编程大神是否还有其他方法。

问题:基本上如果我通过 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)

我想你的意思是:

hello.deposit(dep, bye)

存款方式可以是:

    def deposit(self, dep_amount, account):
        self.cash -= dep_amount
        account.balance += dep_amount

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM