问题
I am aware of the partial
function in functools
, but how common is it in general python programs (not: Haskell, Erlang, Clojure etc ) to write functions to return functions in Python?
for example:
>>> def returnfunk(xs):
... return lambda x: list(filter(lambda y: x == y, xs))
...
>>> fn = returnfunk(["cat", "dog", "horse"])
>>>
>>> (fn("cow") == []) == True
True
>>> (fn("cat") == ['cat']) == True
True
>>>
>>> list(filter(fn, ["zebra", "elephant", "dog", "parrot", "cat"]))
['dog', 'cat']
is it meant for the real (python) world
or more for hobby, academic, interest?
回答1:
The decorators @classmethod
and @staticmethod
are two examples.
回答2:
It's very much used in the real world. The first thing that comes to my mind are APIs with pluggable interfaces. Most operate by implementing a function registry then doing lookups in to that registry.
回答3:
They are very useful. Functional programming uses this kind of thing all the time and it can greatly simplify tasks such as filter
in the way you used above (though there are much easier ways to accomplish what you were trying to do there).
回答4:
It is meant for flexibility. There are a wide variety of things you can do with functions returning functions, like currying, combination and decoration. And of course it allows you to toy with closures, which gives you great flexibility in coding. Whether you need it or not strongly depends on your application.
来源:https://stackoverflow.com/questions/11728511/python-functions-returning-functions