[ACCEPTED]-python factory functions compared to class-function
What I like most about nested functions 11 is that it is less verbose than classes. The 10 equivalent class definition to your maker 9 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 8 you start adding more arguments to the constructor. Then 7 doing it the class way takes an extra line 6 for each argument, while the function just 5 gets the extra args.
It turns out that there 4 is a speed advantage to the nested functions 3 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 2 opcodes involved in the nested functions 1 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
Comparing a function factory to a class 7 is comparing apples and oranges. Use a 6 class if you have a cohesive collection 5 of data and functions, together called an 4 object. Use a function factory if you need 3 a function, and want to parameterize its 2 creation.
Your choice of the two techniques 1 should depend on the meaning of the code.
Nesting functions allows one to create custom 5 functions on the fly.
Have a look at e.g. decorators. The 4 resulting functions depend on variables 3 that are bound at creation time and do 2 not need to be changed afterwards. So using 1 a class for this purpose would make less sense.
More Related questions