老齐python-基础9(函数)

 

继续上篇python

 函数闭包

多参数:函数

>>> def foo(x,y,z,*args,**kargs):
...   print(x)
...   print(y)
...   print(z)
...   print(args)
...   print(kargs)
... 
>>> foo('qiwsir',2,"python")  #多参数各类类型调用适用各类场景
qiwsir
2
python
()
{}
>>> foo(1,2,3,4,5)
1
2
3
(4, 5)
{}
>>> foo(1,2,3,4,5,name="qiwsir")
1
2
3
(4, 5)
{'name': 'qiwsir'}

二、函数对象spa

  递归code

  传递函数对象

>>> def bar():
...   print("I am in bar()")
... 
>>> def foo(func):   #使用func传递函数
...   func()
... 
>>> foo(bar)
I am in bar()
def power_seq(func,seq):
    return [func(i) for i in seq]

def pingfang(x):
    return str(x)   #return x ** 2求平方

if __name__ == "__main__":
    num_seq = [111,3.14,2.91]
    r = power_seq(pingfang, num_seq)
    print(num_seq)
    print(r)

   嵌套函数blog

def foo():
    def bar():
        print("bar() is running")
    bar()
    print("foo() is running")

print(foo())
>>> def foo():
...   a = 1
...   def bar():
...     b = a + 1
...     print("b=",b)
...   bar()
...   print("a=",a)
... 
>>> foo()
b= 2
a= 1
>>> def foo():     #另一种定义方法就会出错Python解析器认定该变量应在bar()内部创建,而不是引用外部对象,因此报错
...   a = 1
...   def bar():
...     a = a + 1
...     print("bar()a=",a)
...   bar()
...   print("foo()a=",a)
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in foo
  File "<stdin>", line 4, in bar
UnboundLocalError: local variable 'a' referenced before assignment

     使用nonlocal解决!递归

>>> def foo():
...   a = 1
...   def bar():
...     nonlocal a 
...     a = a + 1
...     print("bar()a=",a)
...   bar()
...   print("foo()a=",a)
... 
>>> foo()
bar()a= 2
foo()a= 2

    闭包utf-8

#!/usr/bin/env python3
# encoding: utf-8

"""
@version: ??
@author: tajzhang
@license: Apache Licence 
@file: zhongli.py
@time: 2018/2/28 15:50
"""

def weight(g):
    def cal_mg(m):
        return m * g
    return cal_mg

w = weight(10)   #函数对象多层引用,动态函数对象,闭包
mg = w(10)
print(mg)

g0 = 9.78046
w0 = weight(g0)
mg0 = w0(10)
print(mg0)
相关文章
相关标签/搜索