0

Need help for static method

Hi there so im really confused and stuck at this question so i would like to ask for ur help to understand it This is the question: Complete the given code to define a static add() method for the Calculator class, which returns the sum of its parameters. The code takes two numbers as input, and should return their sum using the Calculator class's add() method. And this is the given code but I've added some code to it and got really confused: class Calculator: #your code goes here def__init__(self,n1,n2): self.n1= n1 self.n2= n2 @staticmethod def __add__(n1,n2): return (n1 + n2) n1 = int(input()) n2 = int(input()) print(Calculator.add(n1, n2)) I keep getting an invalid syntax after the def__init__ code and im so confused

29th Apr 2021, 3:11 AM
Zhi Hong
Zhi Hong - avatar
7 Answers
+ 1
Hey! You've forgotten to give a white space between def and __init__ function. Also, in the last line you are using Calculator.add(n1, n2), but Calculator has no attribute named add, it should be __add__ Here is the corrected code: class Calculator: #your code goes here def __init__(self,n1,n2): self.n1= n1 self.n2= n2 @staticmethod def __add__(n1,n2): return (n1 + n2) n1 = int(input()) n2 = int(input()) print(Calculator.__add__(n1, n2))
29th Apr 2021, 4:21 AM
Md. Faheem Hossain
Md. Faheem Hossain - avatar
+ 1
Faheem oh thank you man . Such mistakes do cost me alot of time to find out. Thanks for pointing out!
29th Apr 2021, 5:33 AM
Zhi Hong
Zhi Hong - avatar
+ 1
Faheem yeah my bad tried again ur code it works now
30th Apr 2021, 10:04 AM
Zhi Hong
Zhi Hong - avatar
0
Faheem theres is an error at the __add__ part the codes say its supposed to have only 1 parameter but instead theres 2 (n1,n2)
29th Apr 2021, 6:12 AM
Zhi Hong
Zhi Hong - avatar
0
Faheem update i solved it by changing (n1,n2)to form just 1 parameter (sum)and it works! Thanks for ur help anyway class Calculator: #your code goes here def __init__(self,n1,n2): self.n1= n1 self.n2= n2 @staticmethod def __add__(sum): return (n1 + n2) n1 = int(input()) n2 = int(input()) print(Calculator.__add__(sum))
29th Apr 2021, 6:23 AM
Zhi Hong
Zhi Hong - avatar
0
Zhi Hong your updated code, its working because you're calling n1 and n2 from global scope. Try changing the var of 9 and 10th line, suppose n3 and n4, then it won't work. If you want to make it better, try this one: class Calculator: #your code goes here @staticmethod def __add__(n1,n2): return (n1 + n2) n3 = int(input()) n4 = int(input()) print(Calculator.__add__(n3, n4))
29th Apr 2021, 7:30 AM
Md. Faheem Hossain
Md. Faheem Hossain - avatar
0
Zhi Hong sorry to say that, there wasn't any error in the code. Recheck if you've put everything correctly or not
29th Apr 2021, 7:33 AM
Md. Faheem Hossain
Md. Faheem Hossain - avatar