Skip to content Skip to sidebar Skip to footer

Should I Use A Class? (python)

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 +

Solution 1:

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, and c.

You can also use Python's __call__ special method to allow you to treat the class as though it were a function itself:

classquad:def__init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def__call__(x):
        returnself.a * x**2 + self.b * x + self.c

q = quad(p, q, r)
q(x)

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:

defquad(a, b, c):
    def__quad(x):
        return a * x**2 + b * x + c

    return __quad

Or using lambda syntax:

defquad(a, b, c):
    returnlambda x: a * x**2 + b * x + c

These could then be used like so:

q = quad(p, q, r)
q(x)

Solution 2:

It looks like you are searching for something like currying.

Perhaps this question can help you.

Post a Comment for "Should I Use A Class? (python)"