[callable(obj) for obj in (abs, str, 13)] [True, True, False] #abs是函数,str是类,都可调用
def clip(text:str, max_len:‘int > 0‘=80) -> str: pass
from operator import itemgetter metro_data = [ (‘Tokyo‘, ‘JP‘, 36.933, (35.689722, 139.691667)), (‘Delhi NCR‘, ‘IN‘, 21.935, (28.613889, 77.208889)), (‘Mexico City‘, ‘MX‘, 20.142, (19.433333, -99.133333)) ] for city in sorted(metro_data, key=itemgetter(1)): #根据第2个字段排序 print(city)
cc_name = itemgetter(1, 0) for city in metro_data: print(cc_name(city))
from operator import methodcaller s = ‘The time has come‘ upcase = methodcaller(‘upper‘) upcase(s) #‘THE TIME HAS COME‘ hiphenate = methodcaller(‘replace‘, ‘ ‘, ‘-‘) hiphenate(s) #‘The-time-has-come‘
def cmp1(n1, n2): return n1 - n2 a = [1, 6, 2, 9] print(sorted(a, key=functools.cmp_to_key(cmp1)))
from functools import lru_cache @lru_cache(maxsize=32) def fib(n): print(‘calling the fib function....‘) if n < 2: return n return fib(n-1) + fib(n-2) if __name__ == ‘__main__‘: print(list([fib(n) for n in range(16)])) [print(func) for func in dir(fib) if not func.startswith(‘_‘)] print(fib.cache_info())
import functools def add(a,b): return a + b add3 = functools.partial(add,3) print add3(4)
from functools import reduce ret=reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # 计算的就是((((1+2)+3)+4)+5) print(ret) # 15
from functools import wraps def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print(‘Calling decorated function‘) return f(*args, **kwds) return wrapper
原文:https://www.cnblogs.com/absoluteli/p/14090040.html