types.MethodType 与 functools.partial
这是我的另一个问题的延续(pythonclosure + oop)。在回答这个问题时,Winston Ewert 建议我使用 functools.partial 而不是 types.MethodType。
所以现在我的问题是:两者有什么区别?为什么认为 functool 方式更好?
附:我已经成功地使用 functools.partial 来完成我的关闭,它确实感觉很酷。 :-)
This is a continuation of my other question (python closure + oop). In the answer to that question, Winston Ewert suggested me to use functools.partial
instead of types.MethodType
.
So now my question is: what's the difference between the two? Why is the functool way considered better?
ps. I've managed to use functools.partial for my closure and it did feel cool. :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从实际的角度来看,没有太大区别。 Partial 会柯里化任意数量的参数(在本例中为 1);实例方法会将 self 实例(无论发生什么)传递给包装函数;他们在做同样的事情!
不同之处在于,他们在某种程度上记录了自己;在您链接的问题中;可调用的
closure
不是任何东西的方法;它是一个常规函数,由A
的方法返回;碰巧主体将B
的实例视为第一个参数;但这还不足以使其成为 B 的“方法”。所以这只是风格问题。您正在做的事情看起来更像
functools.partial
,因此您应该使用它,即使您可以使用types.MethodType
实现相同的效果From a practical stand point, there isn't a whole lot of difference. Partial will curry any number of arguments (in this case, 1); an instancemethod will pass the self instance (whatever that happens to be) to the wrapped function; They're doing the same thing!
The difference is that they somewhat document themselves; In your linked question; the
closure
callable isn't a method of anything; it's a regular function, returned by a method ofA
; It happens that the body sees an instance ofB
as the first argument; but that's not enough to make it a "method" of B.So it's just a matter of style. You're doing something that looks more like
functools.partial
, and so you should use that, even though you can achieve the same effect withtypes.MethodType