我应该使用类吗? (蟒蛇) [英] Should I use a class? (Python)
问题描述
我想写一个小的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
除了变量 x
之外( a,b,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!
推荐答案
这看起来像是一个很好的问题,一个类的完美合理使用。基本上你应该考虑使用一个类,当你的程序涉及可以被建模为具有状态的对象的事物。这里,多项式的状态只是系数 a
, b
和 c
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
.
您还可以使用Python的 __ call __
特殊方法该类好像是一个函数本身:
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)
还有一种方法可以稍微干净一点,函数,其中包含那些系数。这实际上是一个例子,如Tichodrama提到:
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
或使用 lambda
语法:
def quad(a, b, c):
return lambda x: a * x**2 + b * x + c
这样可以这样使用:
q = quad(p, q, r)
q(x)
这篇关于我应该使用类吗? (蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!