methodcaller:调用参数指定的方法,实例方法和类方法都可以;
04. Python 冷知识:你可能不知道的三个操作符-itemgetter, attrgetter, methodcaller_哔哩哔哩_bilibili
from operator import itemgetter, attrgetter, methodcaller print("下面演示itemgetter用法:") get_index_zero = itemgetter(0) print(get_index_zero) print(get_index_zero([22,34,11])) print(get_index_zero({0: 'hello', 1:'good'})) print("\n下面演示attrgetter用法:") get_a = attrgetter('a') print(get_a) class T: a = 1000 print(get_a(T)) print(get_a(T())) #实例可以访问类属性 print("\n开始演示methodcaller用法:") bar = methodcaller('bar','hihihi') print(bar) T.bar = lambda self, a :print(a) print(bar(T())) #methodcaller是调用方法的,但这个T.bar是个函数,所以bar(T)调用时会报错 #实例T().bar是个方法 print('\n这种bar是个函数:',T.bar ) print('\n这种bar是个方法:',T().bar ) print(" ") # print("\n此时还没定义下面类方法时,这种会报错:",bar(T)) T.bar = classmethod(lambda cls, a: print(a)) print("\n定义完类方法后,再用这种形式调用就不会报错了:",bar(T))
标签:index,bar,get,Python,print,zero,模块,operator,methodcaller From: https://www.cnblogs.com/bravesunforever/p/17734474.html