Search code examples
pythonmagic-methods

How to change class instance?


This is my Class, below i made two instances h1 and h2, each has different names, then i want to add h2 to h1 like h1.money + h2.money then we supposed to get h1.money = 100. but i dunno how to do that.

class Bank:
    def __init__(self, name):
        self.name = name
        self.money = 50

    def __add__(self, other):
        if isinstance(other, Bank):
            self.money = self.money + other.money
            return Bank(self.name)

    def info(self):
        print(self.money)


h1 = Bank('Br1')
h2 = Bank('Br2')
h1 = h1 + h2

print(h1.name, h1.money)

output: Br1 50


Solution

  • After you modify the money, you should return self.

    class Bank:
        def __init__(self, name):
            self.name = name
            self.money = 50
    
        def __add__(self, other):
            if isinstance(other, Bank):
                self.money = self.money + other.money
                # return Bank(self.name)
                return self
    
        def info(self):
            print(self.money)
    
    
    h1 = Bank('Br1')
    h2 = Bank('Br2')
    h1 = h1 + h2
    
    print(h1.name, h1.money)
    # Br1 100