Programming Terms: Closures - How to Use Them and Why They Are Useful
2019-03-27 15:05
330 查看
文章目录
将函数作为参数传给另一个函数
- 函数接受一个或多个函数作为输入或者函数输出(返回)的值是函数时,我们称这样的函数为高阶函数。
- Python内置函数中,典型的高阶函数是 map 函数,map 接受一个函数和一个迭代对象作为参数,调用 map 时,依次迭代把迭代对象的元素作为参数调用该函数。
def square(x): return x*x def cube(x): return x*x*x
def my_map(func, arg_list): result=[] for i in arg_list: result.append(func(i)) return result squares = my_map(cube, [1,2,3,4,5]) print(squares)
[1, 8, 27, 64, 125]
将函数作为返回值返回
def logger(msg): def log_message(): print('Log',msg) return log_message log_hi = logger("hi") log_hi()
Log hi
def html_tag(tag): def wrap_text(msg): print('<{0}>{1}</{0}>'.format(tag, msg)) return wrap_text print_h1 = html_tag('h1') print_h1('Test Headline!') print_h1('Another Headline!') print_p = html_tag('p') print_p('Test Paragraph!')
<h1>Test Headline!</h1> <h1>Another Headline!</h1> <p>Test Paragraph!</p>
函数可以嵌套
def get_length(text): def clean(t): return t[1:] new_text = clean(text) return len(new_text) get_length("dale")
3
函数可以存储在容器中
foo 是我们自定义的函数,str 和 len 是两个内置函数。for 循环逐个地迭代出列表中的每个元素时,函数对象赋值给了 f 变量,调用 f(“hello”) 与 调用 foo(“hello”) 本质是一样的效果,每次 f 都重新指向一个新的函数对象。当然,你也可以使用列表的索引定位到元素来调用函数。
def foo(x): return x funcs = [str,foo,len] print(funcs)
[<class 'str'>, <function foo at 0x7fcd481f5378>, <built-in function len>]
for f in funcs: print(f("hello"))
hello hello 5
实现了 call 的类也可以作为函数
对于一个自定义的类,如果实现了 call 方法,那么该类的实例对象的行为就是一个函数,是一个可以被调用(callable)的对象。例如:
class mydog: def __init__(self,name,age): self.name = name self.age = age def __call__(self,new_name): self.name = new_name return [self.__str__,self.__repr__] dog = mydog("dog",18) dog("new_dog") dog.name
'new_dog'
- 确定是否是可以被调用的
callable(dog)
True
closures
在计算机科学中,闭包 又称 词法闭包 或 函数闭包,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。闭包被广泛应用于函数式语言中。
# 高阶函数 import logging logging.basicConfig(filename='example.log', level=logging.INFO) # 日志文件 def logger(func): def log_func(*args): logging.info( 'Running "{}" with arguments {}'.format(func.__name__, args)) print(func(*args)) return log_func
def add(x, y): return x+y def sub(x, y): return x-y add_logger = logger(add) sub_logger = logger(sub) add_logger(3, 3) add_logger(4, 5) sub_logger(10, 5) sub_logger(20, 10)
6 9 5 10
引用
本文主要参考下列视频内容,翻译并亲测代码后形成此文,感谢视频作者的无私奉献!
- Programming Terms: Closures - How to Use Them and Why They Are Useful
- Programming Terms: First-Class Functions
参考其他文章如下,感谢作者贡献
相关文章推荐
- Four Logical Relationships of Project Management: What They Are and How To Use Them
- Why Prepared Statements are important and how to use them "properly"
- 为何以及如何使用Netlink Socket ( Why and How to Use Netlink Socket)
- Why Ceph and how to use Ceph?
- 为何以及如何使用Netlink Socket ( Why and How to Use Netlink Socket)
- Why Ceph and how to use Ceph?
- 【翻译】C# Tips & Tricks: Weak References - When and How to Use Them
- Why your Android NDK breakpoints might fail and how to fix them
- Linux Why and How to use NetLink
- Why Ceph and how to use Ceph?
- 802.11 WDS how does it work, when to use it and what are the limitations
- FolderSync :The various features and how to use them
- ceph存储 Why Ceph and how to use Ceph?
- Why and How to Use Netlink Socket
- Why to use memory pool and how to implement it
- Why Ceph and how to use Ceph?
- Why and How to Use Netlink Socket
- (Page 1 of 3 )A walking tour of JavaBeans What JavaBeans is, how it works, and why you want to use it
- (Page 2 of 3 )A walking tour of JavaBeans 2 :What JavaBeans is, how it works, and why you want to use it
- Why and How to Use Netlink Socket