[关闭]
@spiritnotes 2016-06-07T12:30:26.000000Z 字数 720 阅读 1292

Python标准库学习 -- partial

Python DOING


标准库中的partial

将其使用于类中

对于类内部使用,如果采用如下格式,可以发现是不能工作的

  1. class A(object):
  2. def fun(self, a, b, c, z=3):
  3. print(a, b, c, z)
  4. fun_ = partial(fun, z=5)
  5. a = A()
  6. a.fun_(2, 3, 4)
  7. ## 结果如下
  8. Traceback (most recent call last):
  9. File "test2.py", line 14, in <module>
  10. a.fun_(2,3,4)
  11. TypeError: fun() takes at least 4 arguments (4 given)

原因在于在类中使用时其将fun_当成了一个变量,而不是实例函数,这样在处理其调用时并不会将其实际的instance对象也即是self传入。因此需要想办法获得instance并绑定到函数上,采用装饰器可以达到目的:

  1. class classpatial(object):
  2. def __init__(self, func, *args, **keywords):
  3. self.fun = func
  4. self.args = args
  5. self.keywords = keywords
  6. def __get__(self, instance, owner):
  7. return partial(self.fun, *([instance] + list(self.args)), **self.keywords)
  8. class A(object):
  9. def fun(self, a, b, c, z=1):
  10. print(a, b, c, z)
  11. fun_ = classpatial(fun, 3, 4, z=6)
  12. a = A()
  13. a.fun_(5)
  14. ## 结果如下
  15. 3 4 5 6
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注