Reputation: 11
How can I pass in arguments (a
, b
, c
) to a function for a quadratic formula without having to redefine them in the function? I know I could use self.a
instead of just a
inside the formula (same thing for b
and c
) but how do I pass in the argument self.a
as a
, self.b
as b
, and self.c
into the function?
class Calc:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def quadraticformula(self):
c = self.c
b = self.b
a = self.a
neg = ((b*-1)-(sqrt((b**2)-4*a*c)))/(2*a)
pos = ((b*-1)+(sqrt((b**2)-(4*a*c))))/(2*a)
return (pos,neg)
Upvotes: 0
Views: 68
Reputation: 286
You don't have to redefine anything. The __init__
method allows for all other methods of the class to be able to access that variable. So once you actually define a variable you passed to the class (you referenced it as a function, which its not) in the __init__
method all you have to do it just reference it with whatever operation you need.
# within you quadraticformula method
...
neg = ((self.b*-1)-(sqrt(self.b**2 - 4*self.a*self.c)))/(2*self.a)
pos = ((self.b*-1)+(sqrt(self.b**2 - 4*self.a*self.c)))/(2*self.a)
return pos, neg
When passing attributes to the class you have create an instance of it like so:
a = # something
b = # something
c = # something
cl = Calc(a, b, c)
cl.quadraticformula() # call the method (a function with a method) of the function here
# You can call this method in the __init__ method if you want to
# execute as soon as you call the class instead of using the instance
# to reference it
class Calc:
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c
self.quadraticformula
Upvotes: 0
Reputation: 149
Instead of using a class with a constructor function just use a normal function in general
def calc(a, b, c):
neg = ((b*-1)-(sqrt(b**2 - 4*a*c)))/(2*a)
pos = ((b*-1)+(sqrt(b**2 - 4*a*c)))/(2*a)
return pos, neg
Then call the function:
>>> calc(1, 2, -3)
(1.0, -3.0)
Upvotes: 2