程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Python基础:自定义函数

发布于2019-08-08 12:13     阅读(594)     评论(0)     点赞(4)     收藏(3)


函数的形式:

def name(param1, param2, ..., paramN):
    statements
    return/yield value # optional
  • 和其他需要编译的语言(比如 C 语言)不一样的是,def 是可执行语句,这意味着函数直到被调用前,都是不存在的。当程序调用函数时,def 语句才会创建一个新的函数对象,并赋予其名字。
  • Python 是 dynamically typed ,对函数参数来说,可以接受任何数据类型,这种行为在编程语言中称为多态。所以在函数里必要时要做类型检查,否则可能会出现例如字符串与整形相加出异常的情况。

函数的嵌套:

  例:

复制代码
def f1():
    print('hello')
    def f2():
        print('world')
    f2()
f1()
'hello'
'world'
复制代码

  嵌套函数的作用

  • 保证内部函数的隐私
复制代码
def connect_DB():
    def get_DB_configuration():
        ...
        return host, username, password
    conn = connector.connect(get_DB_configuration())
    return conn
复制代码

  在connect_DB函数外部,并不能直接访问内部函数get_DB_configuration,提高了程序的安全性

  • 如果在需要输入检查不是很快,还会耗费一定资源时,可以使用函数嵌套提高运行效率。
复制代码
def factorial(input):
    # validation check
    if not isinstance(input, int):
        raise Exception('input must be an integer.')
    if input < 0:
        raise Exception('input must be greater or equal to 0' )
    ...

    def inner_factorial(input):
        if input <= 1:
            return 1
        return input * inner_factorial(input-1)
    return inner_factorial(input)
print(factorial(5))
复制代码

函数作用域

  1.global

  在Python中,我们不能在函数内部随意改变全局变量的值,会报local variable 'VALUE' referenced before assignment。

  下例通过global声明,告诉解释器VALUE是全局变量,不是局部变量,也不是全新变量
复制代码
VALUE = 10
LIST = ['a','b']
print(id(LIST)) #2490616668744
def validation_check(value):
    global VALUE
    VALUE += 3 #如果注释掉global VALUE,会报local variable 'VALUE' referenced before assignment
    
    LIST[0] = 10 #可变类型无需global可以使用全局变量?
    print(id(LIST)) #2490616668744
    print(f'in the function VALUE: {LIST}') #in the function VALUE: [10, 'b']
    print(f'in the function VALUE: {VALUE}') #in the function VALUE: 13

validation_check(1)
print(f'out of function {LIST}') #out of function [10, 'b']
print(f'out of function {VALUE}') #out of function 13
#a: 13
#b: 13
复制代码

  2.nonlocal

  对于嵌套函数,nonlocal 声明变量是外部函数中的变量

  

复制代码
def outer():
    x = "local"
    def inner():
        nonlocal x # nonlocal 关键字表示这里的 x 就是外部函数 outer 定义的变量 x
        x = 'nonlocal'
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# inner :nonlocal
# outer :nonlocal
复制代码
  当内部变量与外部变量同名时,内部变量会覆盖外部变量
复制代码
def outer():
    x = "local"
    def inner():
        x = 'nonlocal' # 这里的 x 是 inner 这个函数的局部变量
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# 输出
# inner: nonlocal
# outer: local
复制代码

闭包

  • 内部函数返回一个函数
  • 外部函数nth_power()中的exponent参数在执行完nth_power()后仍然会被内部函数exponent_of记住
复制代码
def nth_power(exponent):
    def exponent_of(base):
        return base ** exponent
    return exponent_of # 返回值是 exponent_of 函数

square = nth_power(2) # 计算一个数的平方
cube = nth_power(3) # 计算一个数的立方 
# square
# # 输出
# <function __main__.nth_power.<locals>.exponent(base)>

# cube
# # 输出
# <function __main__.nth_power.<locals>.exponent(base)>

# print(square(2))  # 计算 2 的平方
# print(cube(2)) # 计算 2 的立方
# # 输出
# 4 # 2^2
# 8 # 2^3
复制代码

参考:

  极客时间《Python核心技术与实战 》



所属网站分类: 技术文章 > 博客

作者:天下

链接:https://www.pythonheidong.com/blog/article/14071/458213b76a2fe472e858/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)