@spiritnotes
2016-06-07T12:30:26.000000Z
字数 720
阅读 1452
Python
DOING
对于类内部使用,如果采用如下格式,可以发现是不能工作的
class A(object):
def fun(self, a, b, c, z=3):
print(a, b, c, z)
fun_ = partial(fun, z=5)
a = A()
a.fun_(2, 3, 4)
## 结果如下
Traceback (most recent call last):
File "test2.py", line 14, in <module>
a.fun_(2,3,4)
TypeError: fun() takes at least 4 arguments (4 given)
原因在于在类中使用时其将fun_当成了一个变量,而不是实例函数,这样在处理其调用时并不会将其实际的instance对象也即是self传入。因此需要想办法获得instance并绑定到函数上,采用装饰器可以达到目的:
class classpatial(object):
def __init__(self, func, *args, **keywords):
self.fun = func
self.args = args
self.keywords = keywords
def __get__(self, instance, owner):
return partial(self.fun, *([instance] + list(self.args)), **self.keywords)
class A(object):
def fun(self, a, b, c, z=1):
print(a, b, c, z)
fun_ = classpatial(fun, 3, 4, z=6)
a = A()
a.fun_(5)
## 结果如下
3 4 5 6