与类相比,python 工厂函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/901892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python factory functions compared to class
提问by meade
Just working through learning python and started to look at nested/factory functions (simple example):
刚刚学习python并开始研究嵌套/工厂函数(简单示例):
def maker(N):
def action(X):
return X * N
return action
Are there any advantages of factory functions over creating a class? performance? memory? clean up?
与创建类相比,工厂函数有什么优势吗?表现?记忆?清理?
回答by Theran
What I like most about nested functions is that it is less verbose than classes. The equivalent class definition to your maker function is:
我最喜欢嵌套函数的一点是它比类更简洁。与您的 maker 函数等效的类定义是:
class clsmaker(object):
def __init__(self, N):
self.N = N
def __call__(self, X):
return X * self.N
That doesn't seem so bad until you start adding more arguments to the constructor. Then doing it the class way takes an extra line for each argument, while the function just gets the extra args.
在您开始向构造函数添加更多参数之前,这似乎并没有那么糟糕。然后以类方式为每个参数增加一行,而函数只获取额外的参数。
It turns out that there is a speed advantage to the nested functions as well:
事实证明,嵌套函数也有速度优势:
>>> T1 = timeit.Timer('maker(3)(4)', 'from __main__ import maker')
>>> T1.timeit()
1.2818338871002197
>>> T2 = timeit.Timer('clsmaker(3)(4)', 'from __main__ import clsmaker')
>>> T2.timeit()
2.2137160301208496
This may be due to there being fewer opcodes involved in the nested functions version:
这可能是由于嵌套函数版本中涉及的操作码较少:
>>> dis(clsmaker.__call__)
5 0 LOAD_FAST 1 (X)
3 LOAD_FAST 0 (self)
6 LOAD_ATTR 0 (N)
9 BINARY_MULTIPLY
10 RETURN_VALUE
>>> act = maker(3)
>>> dis(act)
3 0 LOAD_FAST 0 (X)
3 LOAD_DEREF 0 (N)
6 BINARY_MULTIPLY
7 RETURN_VALUE
回答by Ned Batchelder
Comparing a function factory to a class is comparing apples and oranges. Use a class if you have a cohesive collection of data and functions, together called an object. Use a function factory if you need a function, and want to parameterize its creation.
将函数工厂与类进行比较就是在比较苹果和橘子。如果您有一个内聚的数据和函数集合,一起称为对象,请使用类。如果您需要一个函数,并希望参数化它的创建,请使用函数工厂。
Your choice of the two techniques should depend on the meaning of the code.
您对这两种技术的选择应取决于代码的含义。
回答by Stephan202
Nesting functions allows one to create custom functions on the fly.
嵌套函数允许您即时创建自定义函数。
Have a look at e.g. decorators. The resulting functions depend on variables that are bound at creation time and do not need to be changed afterwards. So using a class for this purpose would make lesssense.
看看例如装饰器。结果函数依赖于在创建时绑定的变量,之后不需要更改。因此,为此目的使用类将没有意义。