+ 1

How we can print the value of c in given problems

here is the problems which is related to python oops class Calculator: def __init__(self,a,b): self.a=a self.b=b def add(self,c): return self.a + self.b + c def mul(self): return self.a * self.b def sub(self): return self.a - self.b val1=Calculator(23,1) p=val1.add(4) print(val1.a) print(val1.b)

3rd Apr 2021, 5:46 PM
Runtime Terror
Runtime Terror - avatar
6 Respostas
+ 3
Thank Slick for clearing my doubts
3rd Apr 2021, 6:11 PM
Runtime Terror
Runtime Terror - avatar
+ 2
I want to print the output in this format "Addition of 23 ,1 and 4 is 28 " like this so i need to print the value of parameter c how can i do this this is my code but showing error print(f"Addition of {val1.a},{val1.b} and {p.c} is {p}")
3rd Apr 2021, 5:57 PM
Runtime Terror
Runtime Terror - avatar
+ 2
Is there any method to print c without making self.c variables or not ????
3rd Apr 2021, 6:05 PM
Runtime Terror
Runtime Terror - avatar
+ 1
one way is to make a self.c variable, then assign it to the value that is placed in the add method inside the method itself before returning. that way, you can print out self.c and get the value after the fact.
3rd Apr 2021, 6:01 PM
Slick
Slick - avatar
+ 1
Yeah, you can print everything inside the function. or you can make the variable a global variable Not reccomended. Why? Its 10x easier to just add a 3rd number right at the beggining and then you dont worry about any of this
3rd Apr 2021, 6:09 PM
Slick
Slick - avatar
0
it wouldn't be the value of c. variable c is just a parameter that is added to the solution of self.a and self.b when the add() method is called to print that value: print(val1.add(5)) #print(21 + 1 + 5) # output 29
3rd Apr 2021, 5:50 PM
Slick
Slick - avatar