Python学习之函数进阶

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习之函数进阶相关的知识,希望对你有一定的参考价值。

函数的命名空间

著名的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学习之函数进阶的主要内容,如果未能解决你的问题,请参考以下文章

python学习之函数学习进阶

python学习之函数学习进阶

python学习之函数进阶三

第二模块:03python学习之函数进阶

Python学习之装饰器进阶

基础学习之第十二天(装饰器的进阶)