3.1.1.3 其他callable
partial适用于任何callable对象,而不只是独立的函数。
import functools
class MyClass:
"Demonstration class for functools"
def __call__(self,e,f=6):
"Docstring for MyClass.__call__"
print(' called object with:',(self,e,f))
def show_details(name,f):
"Show details of a callable object."
print('{}:'.format(name))
print(' object:',f)
print(' __name__:',end=' ')
try:
print(f.__name__)
except AttributeError:
print('(no __name__)')
print(' __doc__',repr(f.__doc__))
return
o = MyClass()
show_details('instance',o)
o('e goes here')
print()
p = functools.partial(o,e='default for e',f=8)
functools.update_wrapper(p,o)
show_details('instance wrapper',p)
p()
这个例子从一个包含__call__()方法的类实例中创建部分对象。
运行结果: