第三章:算法-functools:管理函数的工具-修饰符-其他callable

本文展示了如何使用Python的functools.partial函数来创建类实例的部分应用,特别是当类实现了__call__方法时。通过一个具体示例,演示了如何更新包装器并展示callable对象的详细信息。

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__()方法的类实例中创建部分对象。
运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值