码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习之函数进阶

时间:2017-07-30 10:06:05      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:explicit   implicit   www.   关键字   app   修改   complex   执行   int   

函数的命名空间

著名的python之禅

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases arent special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless youre Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, its a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- lets do more of those!

命名空间的分类:(1)全局命名空间(2)局部命名空间(3)内置命名空间

三种命名空间的加载与取值顺序

加载顺序:内置命名空间(程序运行前加载)->全局命名空间(程序运行中:从上到下加载)->局部命名空间(程序运行中:调用时才加载)

取值时分为:局部调用和全局调用

局部调用:局部命名空间->全局命名空间->内置命名空间

x = 1
def f(x):
    print(x)

print(10)

全局调用:全局命名空间->内置命名空间

x = 1
def f(x):
    print(x)

f(10)
print(x)

函数的作用域:按照生效范围可以分为全局作用域和局部作用域。

通过global和local可以更改函数的作用域。

函数的嵌套与作用域:

函数的嵌套

def f1():
    def f2():
        def f3():
            print("in f3")
        print("in f2")
        f3()
    print("in f1")
    f2()
    
f1()

函数的作用域

def f1():
    a=1
    def f2():
        a=2
        def f3():
            a=3
            print("a in f3:",a)

        print("a in f2:",a)
        f3()

    print("a in f1:",a)
    f2()


f1()
def f1():
    a = 1
    def f2():
        a = 2
        print(a in f2 : , a)
    f2()
    print(a in f1 : ,a)

f1()

nonlocal关键字(不是本地的)

使用要求:

1.外部必须有这个变量
2.在内部函数声明nonlocal变量之前不能再出现同名变量
3.内部修改这个变量如果想在外部有这个变量的第一层函数中生效
def f1():
    a = 1
    def f2():
        nonlocal a
        a = 2
    f2()
    print(a in f1 : ,a)

f1()

函数名的本质是函数的内存地址:它可以被引用、被当作容器类型的元素、当作函数的参数和返回值。

闭包函数:

常用方式

def func():
    name = eva
    def inner():
        print(name)
    return inner

f = func()
f()

用途:我们在外部函数调用内部函数时

闭包函数的嵌套:

def wrapper():
    money = 1000
    def func():
        name = eva
        def inner():
            print(name,money)
        return inner
    return func

f = wrapper()
i=f()
print(i)
i()

嵌套了几个就要加括号执行几个

闭包函数的应用:

from urllib.request import urlopen

def index():
    url = "http://www.xiaohua100.cn/index.html"
    def get():
        return urlopen(url).read()
    return get

xiaohua = index()
content = xiaohua()
print(content)

 

Python学习之函数进阶

标签:explicit   implicit   www.   关键字   app   修改   complex   执行   int   

原文地址:http://www.cnblogs.com/1a2a/p/7258214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!