+ 1

Stuck at magic object 76.2

Alright so I've reach magic object but hot so confused at this topic but decided to push through this topic and was stuck at this question: The __add__ method allows for the definition of a custom behavior for the + operator in our class. The provided code is trying to add together two BankAccount objects, which should result in a new object with the sum of the balances of the given accounts. Fix the code to make it work as expected and output the resulting account balance. I added adjusted the given code and this is the code that ive got but i really dont understand how its wrong, i tried following previous examples on the topic but got really confused: class BankAccount: def __init__(self, balance): self.balance = balance def __add__(self,other): return BankAccount (self.balance+ self.balance) a = BankAccount(1024) b = BankAccount(42) result = a + b print(result.balance) Hopefully u guys can help to explain better so i can understand this topic better as well

28th Apr 2021, 7:39 AM
Zhi Hong
Zhi Hong - avatar
6 Antworten
+ 6
I think this is what you need. When you were applying your __add__, you specified (self, other), but then tried to apply (self,self) class BankAccount: def __init__(self, balance): self.balance = balance def __add__(self,other): return BankAccount (self.balance + other.balance) a = BankAccount(1024) b = BankAccount(42) result = a + b print(result.balance) # PS: Well done!
28th Apr 2021, 8:26 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Rik Wittkopp oh gosh thanks mates! Got abit confused there as well but yeah thats exactly the code that i need now that it works thanks so much
29th Apr 2021, 1:53 AM
Zhi Hong
Zhi Hong - avatar
+ 1
this is the correct one class BankAccount: def __init__(self, balance,a,b): self.balance = balance self.a = a self.b = b def __add__(self,other): return BankAccount(self.a + other, self.b + other) a = 1024 b = 42 result = a + b print(result)
1st Sep 2021, 11:29 AM
Hugues Rodrigue Tha Andela
Hugues Rodrigue Tha Andela - avatar
0
Zhi Hong 😁👍
29th Apr 2021, 7:09 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
This is how I solved it. class BankAccount: def __init__(self, balance): self.balance = balance def __add__(self, other_balance): return BankAccount(self.balance + other_balance.balance) a = BankAccount(1024) b = BankAccount(42) result = a + b print(result.balance)
31st Aug 2021, 5:19 PM
No Service
No Service - avatar
0
class BankAccount: def __init__(self, balance): self.balance = balance def __add__(self,other): return BankAccount (self.balance+ other.balance) """self + other""" a = BankAccount(1024) b = BankAccount(42) result = a + b print(result.balance)
23rd Oct 2022, 5:41 AM
Paradox X
Paradox X - avatar