python工厂的功能与上课相比 [英] python factory functions compared to class
问题描述
def maker(N ):
def action(X):
return X * N
返回操作
工厂函数与创建类相比有什么优势吗?性能?记忆?清理?
我最喜欢嵌套函数的地方是它比类的冗长。您的制造商函数的等价类定义是:
pre code class class clsmaker(object):
def __init __(self,N ):
self.N = N
def __call __(self,X):
return X * self.N
直到你开始给构造函数添加更多的参数,这似乎不是很糟糕。然后这样做,class方法会为每个参数添加一行,而函数只是获取额外的参数。
事实证明嵌套有速度优势功能也一样:
>>> 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
这可能是由于涉及较少的操作码嵌套函数版本:
>>> 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
Just working through learning python and started to look at nested/factory functions (simple example):
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?
What I like most about nested functions is that it is less verbose than classes. The equivalent class definition to your maker function is:
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
这篇关于python工厂的功能与上课相比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!