functools有什么功能。部分报价,你不能通过lambdas?
Not much in terms of extra functionality (but, see later) – and, readability is in the eye of the beholder.
Most people who are familiar with functional programming languages (those in the Lisp/Scheme families in particular) appear to like lambda just fine – I say "most", definitely not all, because Guido and I assuredly are among those "familiar with" (etc) yet think of lambda as an eyesore anomaly in Python...
He was repentant of ever having accepted it into Python whereas planned to remove it from Python 3, as one of "Python's glitches".
I fully supported him in that. (I love lambda in Scheme... while its limitations in Python, and the weird way it just doesn't fit in with the rest of the language, make my skin crawl).
然而,对lambda爱好者来说却不是这样——他们上演了Python历史上最接近反叛的事情之一,直到Guido反悔并决定留下lambda。
对functools的一些可能的添加(使函数返回常量、标识符等)并没有发生(以避免显式复制更多lambda的功能),尽管部分保留了(不是完全复制,也不碍眼)。
记住,lambda的主体被限制为一个表达式,所以它有局限性。例如…:
>>> import functools
>>> f = functools.partial(int, base=2)
>>> f.args
()
>>> f.func
<type 'int'>
>>> f.keywords
{'base': 2}
>>>
functools。Partial返回的函数带有用于内省的属性——它所包装的函数,以及它在其中修复的位置和命名参数。此外,已命名的参数可以被重写(在某种意义上,“修复”是设置默认值):
>>> f('23', base=10)
23
所以,正如你所看到的,它肯定没有lambda s: int(s, base=2)那么简单!-)
是的,你可以扭曲你的lambda来给你一些这样的东西——例如,对于关键字重写,
>>> f = lambda s, **k: int(s, **dict({'base': 2}, **k))
但我衷心希望,即使是最狂热的羔羊肉爱好者,也不会认为这种恐怖比部分呼叫更容易读懂!-)。“属性设置”部分甚至更难,因为Python的lambda的“主体是一个单一表达式”的限制(加上赋值永远不能成为Python表达式的一部分)……你最终会“在表达式中伪造赋值”,通过扩展列表理解能力远远超出其设计限制…:
>>> f = [f for f in (lambda f: int(s, base=2),)
if setattr(f, 'keywords', {'base': 2}) is None][0]
现在将命名参数的覆盖性,加上三个属性的设置,合并到一个表达式中,并告诉我这将是多么可读……!