Python 函数作为参数传递

#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
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值