Function in python are first-class objects (runtime / element / argument / return)

1. Treating a Function Like an Object

def test(n):
""" return n*2 """
return n * 2 print test(5) # 10
# '__doc__' is used to generate the help text of an object
# 'help(test)' do like this in Python Interactive Console
print test.__doc__ # ' return n*2 '
# Function object is an instance of the function class.
print type(test) # <type 'function'>
# assign it, call it, use it as an argument
tmp = test
print tmp(5) # 10
print list(map(tmp, range(5))) # [0, 2, 4, 6, 8]

2. Higher-Order Functions

  • A function that takes a function as argument or returns a function
fruits = ['fig', 'apple', 'cherry']

print sorted(fruits, key=len)  # ['fig', 'apple', 'cherry']
# Any one-argument function can be used as the key.
print sorted(fruits, key=lambda word: word[::-1]) # ['apple', 'fig', 'cherry']

2.1 Modern Replacements for map, filter, and reduce

def test(n):
return n * 2 print list(map(test, range(5))) # [0, 2, 4, 6, 8]
print [test(n) for n in range(5)] # [0, 2, 4, 6, 8] print list(map(test, filter(lambda n: n % 2, range(5)))) # [2, 6]
print [test(n) for n in range(5) if n % 2] # [2, 6] print reduce(lambda x,y: x+y, range(100)) # 4950
print sum(range(100)) # 4950

3. The Seven Flavors of Callable Objects

  • User-defined functions: def or lambda.
  • Built-in functions: like len or time.strftime.
  • Built-in methods: like dict.get.
  • Methods: functions in class.
  • Classes: a class runs its __new__ method to create an instance, then __init__ to initialize it, and finally the instance is returned to the caller.
  • Class instances: if a class defines a __call__ method, then its instances may be invoked as functions.
  • Generator functions: functions or methods that use the yield keyword.

[notes]: To determine whether an object is callable, use the callable() built-in function.

4. User-Defined Callable Types

  • Python objects may also be made to behave like functions
class Test:
def __init__(self, items):
self._items = list(items)
def pick(self):
return self._items.pop()
def __call__(self):
return self.pick() t = Test(range(5))
print t.pick() # 4
print t() # 3
print callable(t) # True

5. Keyword-Only Parameters

  • Can only be given as a keyword argument.
  • Python 3 only.
def tag(name, *content, cls=None, **attrs):  # cls: Keyword-Only
""" Generate one or more HTML tags """
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join(' %s="%s"' % (attr, value) for attr, value in sorted(attrs.items()))
else:
attr_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>' % (name, attr_str, c, name) for c in content)
else:
return '<%s%s />' % (name, attr_str)
print(tag('br')) # <br />
print(tag('a', 'hello', 'world', href='#')) # <a href="#">hello</a>\n<a href="#">world</a>
print(tag('div', 'im div~', cls='f-left')) # <div class="f-left">im div~</div>
print(tag(**{'name': 'img', 'id': 'my_img'})) # <img id="my_img" /> def f(a, *, b): # b: Keyword-Only
return a, b
print(f(1, b=2)) # (1, 2)

6. Function Introspection

def test(n):
return n * 2
test.name = 'double it!' # a function uses the __dict__ attribute to store user attributes assigned to it
print test.__dict__ # {'name': 'double it!'}
  • Attributes of functions that don’t exist in plain instances

7. Retrieving Information About Parameters

def test(a, b=2, c=3, **x):
d = a * b * c
return d print test.__defaults__ # (2, 3)
# defaults for keyword-only arguments
# print(test.__kwdefaults__) # {'e': 3}
print test.__code__ # <code object test at 0x...>
# does't include any variable arguments prefixed with * or **
print test.__code__.co_varnames # ('a', 'b', 'c', 'd')
print test.__code__.co_argcount # 3
def test(a, b=2, c=3, **x):
d = a * b * c
return d from inspect import signature # python 3
tmp = signature(test)
print(str(tmp)) # (a, b=2, c=3, **x)
for name, param in tmp.parameters.items():
# 'kind' can also be: VAR_POSITIONAL / VAR_KEYWORD / KEYWORD_ONLY / POSITIONAL_ONLY
print(param.kind) # POSITIONAL_OR_KEYWORD
print(name) # a
print(param.default) # <class 'inspect._empty'> bind_tmp = tmp.bind(**{'a': 11, 'b': 22})
for name, value in bind_tmp.arguments.items():
print(name, '=', value) # a = 11 \n b = 22

8. Function Annotations

  • Just annotation, noting else!
  • Python 3 only.
def test(a:str, b:'in>0'=1) -> str:
return a
print(test('qqq', 2)) # qqq
print(test.__annotations__) # {'a': <class 'str'>, 'b': 'in>0', 'return': <class 'str'>} from inspect import signature # python 3
tmp = signature(test)
for name, param in tmp.parameters.items():
print(param.annotation) # <class 'str'>
print(param.name) # a
print(param.default) # <class 'inspect._empty'>

9. Packages for Functional Programming

9.1 operator

from operator import mul
print mul(4, 5) # 20 from operator import itemgetter # pick items from sequences
test_data = [('b', 2), ('a', 1), ('c', 3)]
for item in sorted(test_data, key=itemgetter(1)): # lambda i: i[1]
print item # ('a', 1)
func = itemgetter(1, 0) # lambda i: (i[1], i[0])
for item in test_data:
print func(item) # (2, 'b') from operator import attrgetter # read attributes from objects
class A:
tmp = 1
class B:
a = A()
class C:
b = B()
tmp = 2
c = C()
func = attrgetter('b.a.tmp', 'tmp')
print func(c) # (1, 2) from operator import methodcaller
s = 'The time has come'
my_upper = methodcaller('upper')
print my_upper(s) # s.upper()
my_replace = methodcaller('replace', ' ', '-')
print my_replace(s) # s.replace(' ', '-') #['abs', 'add', 'and_', 'attrgetter', 'concat', 'contains', 'countOf',
# 'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand',
# 'iconcat', 'ifloordiv', 'ilshift', 'imod', 'imul', 'index', 'indexOf',
# 'inv', 'invert', 'ior', 'ipow', 'irshift', 'is_', 'is_not', 'isub',
# 'itemgetter', 'itruediv', 'ixor', 'le', 'length_hint', 'lshift',
# 'lt', 'methodcaller', 'mod', 'mul', 'ne', 'neg', 'not_', 'or_', 'pos',
# 'pow', 'rshift', 'setitem', 'sub', 'truediv', 'truth', 'xor']

9.2 functools

def test(a, b, c):
return a * b * c from functools import partial
tmp = partial(test, 1, c=2) # can't 'b=2' because 'c'
print list(map(tmp, range(5))) # [0, 2, 4, 6, 8]
print test # <function test at 0x10dca0e60>
print tmp.func # <function test at 0x10dca0e60>
print tmp.args # (1,)
print tmp.keywords # {'c': 2}

5. First-Class Functions的更多相关文章

  1. asp.net MVC helper 和自定义函数@functions小结

    asp.net Razor 视图具有.cshtml后缀,可以轻松的实现c#代码和html标签的切换,大大提升了我们的开发效率.但是Razor语法还是有一些棉花糖值得我们了解一下,可以更加强劲的提升我们 ...

  2. 【跟着子迟品 underscore】Array Functions 相关源码拾遗 & 小结

    Why underscore 最近开始看 underscore.js 源码,并将 underscore.js 源码解读 放在了我的 2016 计划中. 阅读一些著名框架类库的源码,就好像和一个个大师对 ...

  3. 【跟着子迟品 underscore】Object Functions 相关源码拾遗 & 小结

    Why underscore 最近开始看 underscore.js 源码,并将 underscore.js 源码解读 放在了我的 2016 计划中. 阅读一些著名框架类库的源码,就好像和一个个大师对 ...

  4. ajax的使用:(ajaxReturn[ajax的返回方法]),(eval返回字符串);分页;第三方类(page.class.php)如何载入;自动加载函数库(functions);session如何防止跳过登录访问(构造函数说明)

    一.ajax例子:ajaxReturn("ok","eval")->thinkphp中ajax的返回值的方法,返回参数为ok,返回类型为eval(字符串) ...

  5. QM模块包含主数据(Master data)和功能(functions)

    QM模块包含主数据(Master data)和功能(functions)   QM主数据   QM主数据 1 Material   Master MM01/MM02/MM50待测 物料主数据 2 Sa ...

  6. jQuery String Functions

    In today's post, I have put together all jQuery String Functions. Well, I should say that these are ...

  7. 2-4. Using auto with Functions

    在C++14中允许使用type deduction用于函数参数和函数返回值 Return Type Deduction in C++11 #include <iostream> using ...

  8. [Python] Pitfalls: About Default Parameter Values in Functions

    Today an interesting bug (pitfall) is found when I was trying debug someone's code. There is a funct ...

  9. Kernel Functions for Machine Learning Applications

    In recent years, Kernel methods have received major attention, particularly due to the increased pop ...

  10. Execution Order of Event Functions

    In Unity scripting, there are a number of event functions that get executed in a predetermined order ...

随机推荐

  1. selenium3 web自动化测试框架 五: 数据驱动简介及基础使用

    1.数据驱动概述 相同的测试脚本使用不同的测试数据来执行,测试数据和测试行为完全分离,这样的测试脚本设计模式称为数据驱动.简单的理解为数据的改变从而驱动自动化测试的执行,最终引起测试结果的改变.通过使 ...

  2. 为 Exchange 2010 用户添加联系人头像

    一.修改AD架构 为了给联系人添加头像,实际是让联系人头像缩略图能够显示在全局地址列表 GAL 中,需要让其在全局编录(GC)中进行复制,默认情况下,对象的“thumbnailphoto”属性值不会在 ...

  3. 【DSP开发】6455EMIF

     外部设备连接接口包括外部存储器连接接口(EMIF).主机接口(HPI)等.外部存储器接口主要用来同并行存储器连接,这些存储器包括SDRAM.SBSRAM.Flash.SRAM存储器等,外部存储器接口 ...

  4. LIBS+=(20191017)

    1.方式一:(ZC:"LIBPATH"中写路径,"LIBS"中写lib文件名[不带后缀]) LIBPATH += F:/ZC_IDE/VC_3rd/libxml ...

  5. Spring mybatis源码篇章-动态SQL节点源码深入

    通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-动态SQL基础语法以及原理 前话 前文描述到通过mybatis默认的解析驱动类org.apache.ibat ...

  6. Cacls和ICacls

    解释:  Cacls:显示或修改文件的访问控制列表(ACL) ICACLS:显示或修改自由访问控制表(Dacl) 上指定的文件,并指定目录中的文件应用于存储的 Dacl. 总结:显示或修改文件访问控制 ...

  7. Oracle 10g 归档日志满了的解决办法

    如果Oracle的归档日志满了,应用连接数据库就会出错,这时需要手工删除过期的归档日志,方法如下: 1.指定数据库实例 $ export ORACLE_SID=db1 2.进入rman $ rman ...

  8. H3C路由器登录策略专题讲解

    password-control login-attempt login-times [ exceed { lock | lock-time time | unlock } ] undo passwo ...

  9. Android Studio彻底删除Module

    在"Project"视图中选择需要删除的module名,此处删除"app",点击右键,选择"Open Module Setting",然后选 ...

  10. 剑指offer42:数组和一个数字S,输出两个数的乘积最小的

    1 题目描述 输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的. 输出描述: 对应每个测试案例,输出两个数,小的先输出. ...