3.1.1.4 方法和函数
partial()返回一个可以直接使用的callable,partialmethod()返回的callable则可以用作对象的非绑定方法。在下面的例子中,这个独立函数两次被增加为MyClass的属性,一次使用partialmethod()作为methid1(),另一次使用partial()作为method2()。
import functools
def standalong(self,a=1,b=2):
"Standalong function"
print(' called standalong with:',(self,a,b))
if self is not None:
print(' self.attr=',self.attr)
class MyClass:
"Demonstration class for functools"
def __init__(self):
self.attr = 'instance attribute'
method1 = functools.partialmethod(standalong)
method2 = functools.partial(standalong)
o = MyClass()
print('standalong')
standalong(None)
print()
print('method1 as partialmethod')
o.method1()
print()
print('method2 as partial')
try:
o.method2()
except TypeError as err:
print('ERROR:{}'.format(err))
method1()可以从MyClass的一个实例中调用,这个实例作为第一个参数传入,这与采用通常方式定义的方法是一样的。method2()未被定义为绑定方法,所以必须显示传递self参数,否则,这个调用会导致TypeError。