第一类对象 (英语: First-class object) 在计算机科学中指可以在执行期创造并作为参数传递给其他函数或存入一个变量的实体. 将一个实体变为第一类对象的过程叫做 "物件化"(Reification).
什么是一等对象:
在运行时创建
能赋值给变量或数据结构中的元素
能作为参数传递给函数
能作为函数的返回结果
1. 函数身为一个对象, 拥有对象模型的三个通用属性: id, 类型, 和值.
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- def foo():
- print('from foo')
- foo()
- print(id(foo))
- print(type(foo))
- print(foo)
输出
- from foo
- 4406808360
- <class 'function'>
- <function foo at 0x106aa8f28>
2. 函数可以被引用, 即函数可以赋值给一个变量
还可以把该函数赋值给更多的变量, 唯一变化的是该函数对象的引用计数不断地增加, 本质上这些变量最终指向的都是同一个函数对象.
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- def foo():
- print('from foo')
- foo()
- func=foo #引用, 赋值
- print(foo)
- print(func)
- func()
输出
- from foo
- <function foo at 0x10eed8f28>
- <function foo at 0x10eed8f28>
- from foo
3. 函数可以当做参数传递
- def foo():
- print('from foo')
- def bar(func):
- print(func)
- func()
- bar(foo)
输出
- <function foo at 0x1047eff28>
- from foo
4. 函数可以作返回值
函数接受一个或多个函数作为输入或者函数输出 (返回) 的值是函数时, 我们称这样的函数为高阶函数
- def foo():
- print('from foo')
- def bar(func):
- return func
- f=bar(foo)
- print(f)
- f()
输出
- <function foo at 0x107f29f28>
- from foo
5. 函数可以当作容器类型的元素
容器对象 (list,dict,set 等) 中可以存放任何对象, 包括整数, 字符串, 函数也可以作存放到容器对象中
- def foo():
- print('from foo')
- dic={'func':foo}
- foo()
- print(dic['func'])
- dic['func']()
输出
- from foo
- <function foo at 0x10997ef28>
- from foo
6. 函数还可以嵌套
函数嵌套的定义
- def f1():
- def f2():
- print('from f2')
- def f3():
- print('from f3')
- f3()
- f2()
- f1()
输出
from f2 from f3
应用
- def get(text):
- def clean(t): #2
- return t[1:]
- new_text = clean(text) #1
- return len(new_text)
- print(get('python'))
输出
5
高阶函数
把函数作为参数或者返回值为函数的函数就叫做高阶函数
匿名函数
匿名函数顾名思义就是没有名字, 它通过 lambda 关键字创建, 即建即用, 节省了创建函数的时间, 也叫做 lambda 表达式
- fruits = ['strawberry','apple','cherry','banana','pineapple']
- list = sorted(fruits,key=lambda x:x[-1])
- print(list)
- # ['banana', 'apple', 'pineapple', 'strawberry', 'cherry']
上面的 sorted()函数按照水果最后一位字符的顺序排序, 这里并没有什么实际意义, 只是使用 lambda 表达式的一个举例.
可调用对象
函数是对象, 函数名加括号便是调用这个函数, 那么其他对象能否也变成像函数一样可以加括号调用呢
这是可以的, 只需要在类中实现特殊方法 call
- class Fruit():
- def __init__(self,name):
- self.name = name
- def __call__(self, *args, **kwargs):
- print(self.name+'was called')
- apple = Fruit('apple')
- apple() # apple was called
call 方法还可以添加任意的参数, 和函数一样.
对于一个对象可不可以被调用可以通过 callable()函数判断
- print(callable(apple)) # True
- print(callable(Fruit)) # True
能够调用就会返回 True. 这里我们发现 Fruit 同样也可以调用, 这是因为类同样也是一个对象, Fruit 也是一个实例, 创造它的类也实现了 call 方法, 这里就不细说了.
参考: https://www.cnblogs.com/smallmars/p/6936871.html
https://www.cnblogs.com/sfencs-hcy/p/10454125.html https://www.cnblogs.com/sfencs-hcy/p/10454125.html
来源: http://www.bubuko.com/infodetail-3101061.html