簡體   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