I'm trying to write a small Python module which contain some mathematical functions. For example, it might contain a function like:
def quad(x, a, b, c):
return a*x**2 + b*x + c
As you may notice it contains several parameters (viz. a, b, c
) apart from the variable x
. Now if I were to put this in a file and simply import it, the end user would have to always call the function with the parameters in addition to the variable. Because of this I was thinking of creating a class such as this:
class quad:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def eq(x):
return self.a*x**2 + self.b*x + self.c
Thus allowing the end user to use it as:
q = quad(p, q, r)
eq = q.eq
Is this the right way of doing things? I am terribly sorry about the title of the question, as I couldn't think of a better one!
That seems like a perfectly reasonable use of a class. Essentially you should consider using a class when your program involves things that can be modelled as objects with state. Here, the "state" of your polynomial is just the coefficients
a
,b
, andc
.You can also use Python's
__call__
special method to allow you to treat the class as though it were a function itself:Yet another way of doing it, which could be slightly cleaner, would be simply to return a function with those coefficients baked into it. This is essentially an example of currying, as Tichodrama mentions:
Or using
lambda
syntax:These could then be used like so:
It looks like you are searching for something like currying.
Perhaps this question can help you.