python functions returning functions [closed]

╄→尐↘猪︶ㄣ 提交于 2021-02-08 09:15:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!