函数(二)

函数(二)

函数对象

函数本身是一个对象,可以赋值给一个变量

def show_fruit():
    print('i like eat fruits')
    return None


a = show_fruit
show_fruit()
a()


# 执行结果如下,这时候 a() 和 show_fruit()的执行结果一模一样,两个是同一种东西
# i like eat fruits
# i like eat fruits

函数嵌套

函数中可以有另一个函数,当执行外面的函数,里面的函数也会被执行

def show_max_num(num_a, num_b):
    if num_a > num_b:
        return num_a
    else:
        return num_b


def max_num(num_a, num_b, num_c, num_d):
    res = show_max_num(num_a, num_b)
    res = show_max_num(res, num_c)
    res = show_max_num(res, num_d)
    print(f'the biggest number is {res}')
    return res


max_num(10, 12, 8, 9)

名称空间与作用域

注意:

加载顺序:内置命名空间,全局命名空间,局部命名空间

查找循序:局部命名空间,全局命名空间,内置命名空间

作用域

x = 10
print(x)


def test():
    x = 5
    print(x)


test()
print(x)
# 输出结果是
# 10
# 5
# 10

闭包函数

def outter(x):
    def show():
        print(x)

    return show


f = outter('www.baidu.com')
f()
f = outter('www.taobao.com')
f()
f()
f()
# 因为使用了闭包,每次执行函数后,可以省去输入参数的步骤

装饰器

最简单的装饰器

def deco(func):
    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        print('good bye')
        return res

    return wrapper


def say_hello(name):
    print(f'hello,{name}')


say_hello = deco(say_hello)
say_hello('xiaoli')

使用了语法糖后,请比较一下区别

def deco(func):
    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        print('good bye')
        return res

    return wrapper

# say_hello = deco(say_hello)
@deco
def say_hello(name):
    print(f'hello,{name}')


say_hello('xiaoli')



迭代器

可迭代对象是:字符串,列表,元组,字典,集合,文件。他们有内置__iter__方法,执行次方法,拿到的返回值就是迭代器对象

我们用while实现遍历字符串中所有内容并输出

str_test = 'i need more money.'
str_test = str_test.__iter__()
while True:
    try:
        print(str_test.__next__())
    except Exception as e:
        break

三元表达式和列表推导式

不推荐使用,因为太装逼,

但是,我们虽然不鼓励装逼,但要学会如何识破别人装逼

# 三元表达式
a = 10
b = 20
print('a比较大' if a > b else 'a并不比b大')
# 列表推导式
print([i * 2 for i in range(10)])
# 组合拳
print([i + 1 if i % 2 == 0 else i for i in range(20)])

字典生成式

字典生成式配合zip函数,一套组合拳下来,快速生成字典

dic = {k: v for k, v in zip('abcde', ('apple', 'banana', 'cherry', 'dog', 'english'))}
print(dic)
# 执行结果
# {'a': 'apple', 'b': 'banana', 'c': 'cherry', 'd': 'dog', 'e': 'english'}

生成器

def func():
    print('from 01')
    yield 'a'
    print('from 02')
    yield 'b'
    print('from 03')
    yield 'c'


g = func()
for i in g:
    print(i)

转载于:https://www.cnblogs.com/heroknot/p/10969869.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值