Python 函数作为参数传递

来源:互联网 发布:淘宝真人秀从哪里看 编辑:程序博客网 时间:2024/04/29 06:26
#map()的功能是将函数对象依次作用于表的每一个元素,每次作用的结果储存于返回的表re中。
#map通过读入的函数(这里是lambda函数)来操作数据
def test_func_map():
    re = map((lambda x: x+3), [1, 2, 3, 4])
    print re


def testA(a, b, **kargs):
    print a+b
    print "testA: %s" % kargs


#函数作为参数传递
def test_func(func, a, b, **kargs):
    func(a, b)
    print "test_func: %s" % kargs
    
#函数作为参数传递
def test_func_lambda(func, **kargs):
    func()
    print "test_func_lambda: %s" % kargs


def test_func_getattr():
    func = getattr(obj, "testA")
    func(1, 2)


class TestGetattr():
    aa = "2a"
    def get_attr(self):
        print "test getattr()"
    
    def print_text(self):
        print "print text"
    
    def print_string(self):
        print "print string"


#getattr(obj, "a")的作用和obj.a是一致的,但该方法还有其他的用处,最方便的就是用来实现工厂方法
#根据传入参数不同,调用不同的函数实现几种格式的输出
def output(print_type="text"):
    tg = TestGetattr()
    output_func = getattr(tg, "print_%s" % print_type)
    output_func()


if __name__ == "__main__":
    #test_func(testA, 1, 2, aa="aa")
    #test_func_lambda((lambda: testA(1, 2, bb="bb")), cc="cc")
    #test_func_map()
    #test_func_getattr()
    
    #getattr方法,传入参数是对象和该对象的函数或者属性的名字,返回对象的函数或者属性实例
    obj = TestGetattr()
    func = getattr(obj, "get_attr") #getattr()获得对象的属性和方法
    func()
    
    print getattr(obj, "aa") #完成对象的反射
    print obj.aa
    
    #callable方法,如果传入的参数是可以调用的函数,则返回true,否则返回false。
    print callable(getattr(obj, "aa"))
    
    output("string")
0 0
原创粉丝点击