码迷,mamicode.com
首页 > 其他好文 > 详细

functools:管理函数工具(部分)

时间:2014-07-06 13:04:55      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:style   使用   art   for   管理   python   

# -*- coding: utf-8 -*-

# python:2.x

__author__ = ‘Administrator‘

#functools:管理函数工具

#作用:处理其他函数的函数

#版本:2.5及之后

#用于调整或者扩展函数和其他可回调对象,不用重写

#修饰符:主要工具是partial在,用于包装,一个有默认参数可回调对象。得到对象本身是可回调的,可以看作就像是原来的函数,它与原函数完全相同,调用时也可以提供额外的位置或者命名参数,可以使用partial而不是lambda提供的默认参数,有些参数可不指定

#partial对象

import functools

def myfunc(a,b=2):

    ‘‘‘docstring for myfunc().‘‘‘

    print ‘ called myfunc with:‘,(a,b)

    return

def show(name,f,is_partial=False):

    print name

    print f

    if not is_partial:

        print f.__name__

    if is_partial:

        print f.func

        print f.args

        print f.keywords

    return

show(‘myfunc‘,myfunc)

myfunc(‘a‘,3)

print

p1=functools.partial(myfunc,b=4)

show(‘partial with named default‘,p1,True)

p1(‘passing a‘)

p1(‘override b‘,b=5)

#p1()#TypeError: myfunc() takes at least 1 argument (1 given)

#获取函数属性

#默认情况下,partial对象没有__name__或者__doc__属性。如果没有这些属性,修饰函数更加难调试,使用update_wrapper()可以将原函数属性或者添加到oartial对象

def myfunc1(a,b=2):

    ‘‘‘docstring for myfunc().‘‘‘

    print ‘ called myfunc with:‘,(a,b)

    return

def show2(n,f):

    print n

    print f

    print ‘__name__‘

    try:

        print f.__name__

    except AttributeError,s:

        print ‘no __name__‘,s

    print repr(f.__doc__)

    print

    return

show2(‘myfunc1‘,myfunc1)

p1=functools.partial(myfunc1,b=4)

show2(‘raw wrapper‘,p1)

print functools.WRAPPER_ASSIGNMENTS

print functools.WRAPPER_UPDATES

functools.update_wrapper(p1,myfunc1)

show2(‘updated wrapper‘,p1)

#其他可回调#Paryisl适用于任何可回调对象,而不只是单独的函数

class MyClass(object):

    def method1(self,a,b=2):

        print self,a,b

        return

    def methond2(self,c,d=5):

        print self,c,d

        return

    wrapp=functools.partial(methond2,‘wrapped c‘)

    functools.update_wrapper(wrapp,methond2)

 

    def __call__(self,x,z=6):

        print self,x,z

        return

 

def show_update(n,f):

    print n

    print f

    print ‘__name__‘

    try:

        print f.__name__

    except AttributeError,s:

        print ‘no __name__‘,s

    print repr(f.__doc__)

    print

    return

o=MyClass()

show_update(‘method1 straight‘,o.method1)

o.method1(‘on default for a‘,b=3)

print

p1=functools.partial(o.method1,b=4)

functools.update_wrapper(p1,o.method1)

show_update(‘method1 wrarer‘,p1)

functools:管理函数工具(部分),布布扣,bubuko.com

functools:管理函数工具(部分)

标签:style   使用   art   for   管理   python   

原文地址:http://www.cnblogs.com/mhxy13867806343/p/3826105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!