+ 2

I'm getting typeerror in python don't know why ?

Code: class Calculator: def Add(a, b): return a+b def Sub(a, b): return a-b def Mul(a, b): return a*b def Div(a, b): return a/b C1=Calculator() Ans=C1.Add(2, 3) print("Addition ="+Ans) Ans=C1.Sub(3, 2) print("Subtraction ="+Ans) Ans=C1.Mul(2, 3) print("Multiplication ="+Ans) Ans=C1.Div(4, 2) print("division ="+Ans) Error: Traceback (most recent call last): File "./Playground/file0.py", line 12, in <module> Ans=C1.Add(2, 3) TypeError: Add() takes 2 positional arguments but 3 were given What am I doing wrong?

31st Aug 2024, 10:51 AM
Abhishek Shelar
Abhishek Shelar - avatar
3 Antworten
+ 3
Abhishek Shelar , 2 issues: > the functions in class `Calculator` all requires `self` as first parameter. > `Ans` is a numerical value (int or float), so we can not concatenate it to the string of: `"Addition ="`. better to use like this: print("Addition =", Ans)
31st Aug 2024, 11:02 AM
Lothar
Lothar - avatar
+ 2
or you can define the methods as staticmethods: class Calculator: @staticmethod def Add(a, b): print('Addition =', a+b) @staticmethod def Sub(a, b): print('Subtraction =', a-b) @staticmethod def Mul(a, b): print('Multiplication =', a*b) @staticmethod def Div(a, b): print('Division =', a/b) C1 = Calculator C1.Add(2, 3) C1.Sub(3, 2) C1.Mul(2, 3) C1.Div(4, 2) #or Calculator.Add(2,3) Calculator.Sub(3,2)
31st Aug 2024, 12:40 PM
Bob_Li
Bob_Li - avatar
+ 1
Thanks for the help my error is solved I knew about the self but I had no idea about the second one thanks Lothar
31st Aug 2024, 11:08 AM
Abhishek Shelar
Abhishek Shelar - avatar