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
CodePudding user response:
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
CodePudding user response:
Bank.__init__
should take an additional argument to let you set the initial value.
class Bank:
def __init__(self, name, money=50):
self.name = name
self.money = money
def __add__(self, other):
if isinstance(other, Bank):
money = self.money other.money
return Bank(self.name, money)
return NotImplemented
def info(self):
print(self.money)
NotImplemented
is returned when other
is not an instance of Bank
so that other.__radd__
gets a chance to define the operation. In general, __add__
should not modify either of its arguments (but see below).
You might also consider whether when (or if) it makes sense to add two Bank
instances together. For example, what if the two Bank
s you are adding have different names; do you really want to just take the first one's name, ignoring the second?
Finally, if you really want to modify a bank in-place as suggested by your original code, implement Bank.__iadd__
as well:
def __iadd__(self, other):
if isinstance(other, Bank):
self.money = other.money
return self
return NotImplemented
Then
h1 = h2 # h1.__iadd__(h2)