简体   繁体   English

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

[英]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.

相关问题 为什么我不能更改对象实例的 __class__ 属性? - Why can't I change the __class__ attribute of an instance of object? 为什么我不能在python中更改另一个模块变量? - Why can't I change another modules variable in python? 在Django中创建另一个实例后,如何更改从模型类实例派生的变量? - How can I make a variable derived from a model class instance change as soon as another instance is created in Django? 为什么我不能从另一个类Python访问变量 - Why can't I access a variable from another class Python 为什么我不能从函数内部更改全局变量? - Why can't I change a global variable from inside a function? 为什么我不能更改变量的数据类型? - Why can't I change the dtype of a variable? 从另一个类更改实例变量 - change an instance variable from another class AttributeError:'guiCreate'对象没有属性'master'-为什么我不能从另一个类访问函数? - AttributeError: 'guiCreate' object has no attribute 'master' - Why can't i access functions from another class? 如何从 Python 中的另一个类更改变量的值? - How can I change the value of a variable from another class in Python? 如何更改一个函数中的 Bool 变量? - How can I change a Bool variable in one function from another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM