Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

python - 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). Instead, I must invoke another instance method through another object instance method. 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.

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) + ''+ 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)+''+'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)
question from:https://stackoverflow.com/questions/65641760/why-cant-i-change-an-instance-variable-from-another-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...