简体   繁体   中英

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 + 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 , 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:

class quad:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __call__(x):
        return self.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:

def quad(a, b, c):
    def __quad(x):
        return a * x**2 + b * x + c

    return __quad

Or using lambda syntax:

def quad(a, b, c):
    return lambda x: a * x**2 + b * x + c

These could then be used like so:

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

It looks like you are searching for something like currying .

Perhaps this question can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM