2024-06-05 拷贝、函数、装饰器、迭代生成器

一、浅拷贝

lists = [1,2,[6]]

内存空间不同,浅拷贝内容不变 

new_lists=copy(lists)
lists.append(7)
print(lists,new_lists)      //[1,2,[6],7]  [1,2,[6]]

改变列表中内容,内存空间相同,数值改变

new_lists=copy(lists)
lists[-1].append(7)
print(lists,new_lists)   //[1,2,[6,7]]

二、函数

1.返回值

可以返回多个值,元组类型。

def hello():
    return 123,456,789
print(hello())         //(123,456,789)

交换变量值

a=22
b=33
a,b = b,a
print(a,b)    //33,22

返回值-----yield 生成器遍历打印

def get_data(num):
    x = 0
    y = 1
    for i in range(num):
        x,y = y,x+y
        yield x            //生成器    得到一个值输出一次

for i in get_data(10):
         print(i) 

2.不定长函数※

*args返回元组类型,args可以换成其他

def hello(*args):
    print(min(args))
    
hello(5,2,1,6,3)        //(5,2,1,6,3)

 **kwargs返回字典类型,kwargs可以换成其他

def hello(**kwargs):
    print(kwargs)
hello(nihao ='谢谢',byeby = '再见')     //{'nihao': '谢谢', 'byeby': '再见'}

3.空函数

del hello():
    pass                  //空函数pass占位

del hello():
    while True:
          print(1)
          return          //返回None,并退出循环,结束函数进程

 4.参数

确定数值写在变量后面

defhello(name,age=15):

1.位置传值

def hello(x,y):
    print(x,y)
hello(1,2)       //位置对应传值   1 2

2.变量传值 

def hello(x,y):
    print(x,y)
hello(y = 2,x = 6)    //根据对应变量传值  6 2

 求最大值

def get_max(*args):
    max = args[0]
    for i in args:
        if max < i:
            max = i
    return max
print(get_max(12,5,6,4))        

3.关键字参数

def info (name,*,city):
    print('姓名:',name,'城市:',city)

info('王伟',city ='上海')   //*后面表示该参数不能直接传值,必须用关键字传值    

5.递归函数

自己调用自己

def get_data(n):
    if n==1:
        return 1
    return n+get_data(n-1)
print(get_data(100))          //斐波那契数列  5050
    

6.装饰器

装饰器是一个接受函数对象作为参数并返回一个新函数的函数。

测试函数运行时间,从开始到结束

import time
def my_decorator(func):
    def wrapper(*args,**kwargs):
        begin_time = time.time()
        data=func()                     //func()调用say_hello(),记录结束时间
        stop_time = time.time()
        print(stop_time-begin_time)
        return data
    return wrapper

@my_decorator
def say_hello():                        //Hello!
    time.sleep(3)                         3.06215522
    print("Hello!")                       None   say_hello返回值,没有return所以返回None
                                          
print(say_hello())                      //打印say_hello返回值
@my_decorator装饰器装饰say_hello(),实际上是将say_hello()函数作为参数传递给my_decorator,然后返回wrapper函数。
调用say_hello(),实际上是在调用wrapper函数,先记录开始时间,再调用原始的say_hello()函数,记录结束时间,计算并打印执行时间,最后返回say_hello()的返回值。

7.迭代

可迭代对象-->迭代器-->生成器 能被for循环遍历的元素

迭代器:能被next函数调用,并不断返回下一个值

迭代器包含1.生成器    2.被强制转成迭代器

lista = [1,2.3,4]
new_lists = iter(lists)   //强制转迭代器
print(next(new_lists))
print(next(new_lists))
print(next(new_lists))

生成器

data1 = (x for x in range(100))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值