iis服务器助手广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python学习(day4)
  • 179
分享到

python学习(day4)

python 2023-01-31 01:01:06 179人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

1、装饰器:''' 实现装饰器只是储备: 1、函数即“变量” 2、高阶函数 3、嵌套函数 高阶函数+嵌套函数=》装饰器 ''' import time def timmer(func):     def warpper(*args,**k

1、装饰器:

'''
实现装饰器只是储备:
1、函数即“变量”
2、高阶函数
3、嵌套函数

高阶函数+嵌套函数=》装饰器
'''
import time
def timmer(func):
    def warpper(*args,**kwargs):
        start_time = time.time()
        func()
        stop_time = time.time()
        print("the func run time is %s"%(stop_time-start_time))
    return warpper

@timmer
def test1():
    time.sleep(3)
    print("in the test1")

test1()
import time

user,pwd = "alex","123"
def auth(auth_type):
    def outer_wrapper(func):
        print("auth func:",auth_type)
        def wrapper(*args,**kwargs):
            print("auth func args:",*args,**kwargs)
            if auth_type=="local":
                username = input("username:").strip()
                passWord = input("password:").strip()
                if user == username and pwd ==password:
                    print("\033[32;1m user has passed authentication\033[0m")
                    res = func(*args,**kwargs)
                    print("-----c----")
                    return res
                else:
                    exit("\033[31;1m invalid username or password\033[0m")
            elif auth_type=="ldap":
                print("ldap,不会")
        return wrapper
    return outer_wrapper


def index():
    print("welcome to index page")
@auth(auth_type="local")
def home():# home = wrapper()
    print("welcome to home page")
    return print("from home")
@auth(auth_type="ldap")
def bbs():
    print("welcome to bbs page")

index()
home()#wrapper()
bbs()

2、迭代器:

from collections import Iterable#Iterable可迭代对象
print(isinstance([],Iterable))#判断一个对象是否是Iterable可迭代对象
print(isinstance(100,Iterable))#判断一个对象是否是Iterable可迭代对象

from collections import Iterator#Iterator迭代器
print(isinstance((i for i in range(10)),Iterator))#判断一个对象是否是Iterator迭代器
print(isinstance(iter([]),Iterator))#iter()方法可把一个Iterable可迭代对象,变成一个Iterator迭代器

3、生成器:

'''
生成器 :generator
只有在调用时才会生成相应的数据
只记录当前位置
只有一个__nest()__方法。next()
'''
import time
def consumer(name):
    print("%s 准备吃包子啦!" %name)
    while True:
       baozi = yield

       print("包子[%s]来了,被[%s]吃了!" %(baozi,name))

# c = consumer("liudeyi")
# c.__next__()
# c.send("韭菜馅")

def producer(name):
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("老子开始准备做包子啦!")
    for i in range(10):
        time.sleep(1)
        print("做了1个包子,分两半!")
        c.send(i)#send给generator的value会成为当前yield的结果 并且send的返回结果是下一个yield的结果(或者引发StopIteration异常)
        c2.send(i)

producer("alex")

# a=[]
# print(dir(a))#查看a下所有可调用方法

4、斐波那契数列:

def fib(max):
    n,a,b = 0,0,1
    while n < max:
        #print(b)
        yield b#有 yield 的函数在 python 中被称之为 generator(生成器)
        a,b = b,a+b
        n = n+1
    return "done"
f = fib(100)

while True:
    try:
        x = next(f)
        print('f:',x)
    except StopIteration as e:#异常处理
        print('Generator return value:',e.value)
        break

# print(f.__next__())
# print('=========')
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())

# print('=====da=======')
# for i in f:
#     print(i)

5、匿名函数:

calc = lambda x:x*3
print(calc(3))

6、列表生成式:

#列表生成式:
l = [i*2 for i in range(10)]
print(l)

b = (i*2 for i in range(10))
print(b)
print(b.__next__())
for i in b:
    print(i)

7、内置方法:

#Http://www.cnblogs.com/alex3714/articles/5740985.html
#https://docs.Python.org/3/library/functions.html?highlight=built
print(all([0,1,2,-8]))#如果iterable的所有元素不为0、''、False或者iterable为空,all(iterable)返回True,否则返回False
print(any([]))#如果iterable的任何元素不为0、''、False,all(iterable)返回True。如果iterable为空,返回False
print(ascii([1,2,'撒的发生']))
print(bin(255))#将整数x转换为二进制字符串

#res = filter(lambda n:n%2==0,range(100))#函数包括两个参数,分别是function和list。该函数根据function参数返回的结果是否为真来过滤list参数中的项,最后返回一个新列表
res = map(lambda n:n*n,range(10))#map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
for i in res:#lambda:匿名函数
    print(i)

import functools
res = functools.reduce(lambda x,y:x*y,range(1,10,2))#functools.reduce等同于内置函数reduce()
print(res)#reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

print(globals())#globals 函数返回一个全局变量的字典,包括所有导入的变量
print(hex(255))#转16进制
print(oct(255))#转8进制
print(round(1.1314,2))#保留两位小数

a = {3:4,1:3,7:2,-7:9,2:5}
print(sorted(a.items()))#sorted排序,按key排序
print(sorted(a.items(),key=lambda x:x[1]))#按value排序

a = [1,2,3,4]
b = ['a','b','c','d']
for i in zip(a,b):#zip拉链
    print(i)
#......

8、软件目录结构规范:

Foo/
|-- bin/
|   |-- foo
|
|-- foo/
|   |-- tests/
|   |   |-- __init__.py
|   |   |-- test_main.py
|   |
|   |-- __init__.py
|   |-- main.py
|
|-- docs/
|   |-- conf.py
|   |-- abc.rst
|
|-- setup.py
|-- requirements.txt
|-- README

注:

  1. bin/: 存放项目的一些可执行文件,当然你可以起名script/之类的也行。

  2. foo/: 存放项目的所有源代码。(1) 源代码中的所有模块、包都应该放在此目录。不要置于顶层目录。(2) 其子目录tests/存放单元测试代码; (3) 程序的入口最好命名为main.py

  3. docs/: 存放一些文档。

  4. setup.py: 安装、部署、打包的脚本。

  5. requirements.txt: 存放软件依赖的外部Python包列表。

  6. README: 项目说明文件。

--结束END--

本文标题: python学习(day4)

本文链接: https://www.lsjlt.com/news/184332.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python学习(day4)
    1、装饰器:''' 实现装饰器只是储备: 1、函数即“变量” 2、高阶函数 3、嵌套函数 高阶函数+嵌套函数=》装饰器 ''' import time def timmer(func):     def warpper(*args,**k...
    99+
    2023-01-31
    python
  • Python-基础-day4
     深浅copy                          1、先看赋值运算 h1 = [1,2,3,['aihuidi','hhhh']] h2 = h1 h1[0] = 111 print(h1) print(h2) #结果:...
    99+
    2023-01-30
    基础 Python
  • Python学习
    Python是创始人吉多•范罗苏姆(Guido van Rossum)在1989年圣诞节期间,在阿姆斯特丹,为了打发圣诞节的无趣,决心开发一个新的脚本解释程序,而在给自己新创造的计算机语言起名字的时候,由于其是,自于七十年代风靡全球的英国六...
    99+
    2023-01-31
    Python
  • 学习python
    亲爱的朋友:     欢迎你!很高兴能在这里见到你,你能来到这里说明你真的很喜欢python,很想把python给学好!我觉的你很幸运,开始我学python的时候比较少资料,学起来也比较头疼,现在随着python越来越流行,资料也越来越多,...
    99+
    2023-01-31
    python
  • Python 学习
    第一次学习python查阅的资料一,熟悉基本在正式介绍python之前,了解下面两个基本操作对后面的学习是有好处的:1)基本的输入输出 可以在Python中使用+、-、*、/直接进行四则运算。11+3*3查看全部10(2)导入模块 使用im...
    99+
    2023-01-31
    Python
  • Python学习:Python form
    从Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。 相对基本格式化输出采用‘%’的方法,format()功能更强大,该...
    99+
    2023-01-31
    Python form
  • python学习笔记--趣学Python
    由反弹球和球拍构成的游戏。球会在屏幕上飞过来,玩家要用球拍把它弹回去 画布和画弹球 引入模块 #Tkinter -- Python的标准GUI库,Tk 接口,是python 内置的安装包 from tkinter import * i...
    99+
    2023-01-31
    学习笔记 python Python
  • python学习(day3)
    1、集合的使用:#1、集合的操作: list_1 = [1,4,5,7,3,6,7,9] list_1 = set(list_1)#创建集合 list_2 = set([2,6,0,22,66,8,4]) print(list_1,typ...
    99+
    2023-01-31
    python
  • Python学习day01
    age = 23 count=0 while count<3: guess_age = int (input("My age:")) if age ==guess_age: print("n...
    99+
    2023-01-30
    Python
  • python学习_18
    字典字典是无序的字典的key只能是不可变对象,不能是list dict创建字典创建空字典,并赋值 d = {}d["name"] = "huhongqiang"d["sex"] = "M"d["height"] = 170d{'nam...
    99+
    2023-01-31
    python
  • python学习(8)
    退出双层循环:方式1:try--except try: for i in range(5): for j in range(5): if i==3 and j ==3: ...
    99+
    2023-01-31
    python
  • Python学习-logging
    Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志。logging的日志可以分为debug(),info(),warning(),error()和...
    99+
    2023-01-31
    Python logging
  • python学习:Indentation
    Python语言是一款对缩进非常敏感的语言,给很多初学者带来了困惑,即便是很有经验的Python程序员,也可能陷入陷阱当中。最常见的情况是tab和空格的混用会导致错误,或者缩进不对,而这是用肉眼无法分别的。在编译时会出现这样的错Indent...
    99+
    2023-01-31
    python Indentation
  • python学习--DataFrame
    目录 一、DataFrame对象的创建 1、根据列表创建: 情况1:由二维列表 情况2:由元组tuple组成的列表 情况3:由字典dict组成的列表 情况4:由数组array组成的列表 情况5:由序列series组成的列表 2、根据字典创...
    99+
    2023-10-02
    python 开发语言 pandas
  • Python学习 (1)
    一、基本语法: import 与 from...import 在 python中 用import 或者from...import 来导入相应的模块。 将整个模块(somemodule)导入,格式为:import somemodule 从...
    99+
    2023-01-30
    Python
  • Python学习教程(Python学习路线):Python——SciPy精讲
    Python学习教程(Python学习路线):Python——SciPy精讲SciPy 是 Python 里处理科学计算 (scientific computing) 的包,使用它遇到问题可访问它的官网 (https://www.scipy...
    99+
    2023-06-02
  • python-flask学习
    学习了一段时间python之后,因为一些现实要求和个人学习需要,所以开始对flask进行学习。找了一些博客和一本书《Flask Web开发》,书还没怎么仔细看,目前跟着博客学,还是有一些收获。下面将我觉得写的比较好的博客推荐一下。 duk...
    99+
    2023-01-30
    python flask
  • python学习(二)
    #浏览器GET请求,发送的参数有中文时,需要编码再拼接参数发送from urllib import requestimport urlliburl = r"http://www.baidu.com/s"#百度搜索 浏览器userage...
    99+
    2023-01-31
    python
  • python学习----------so
    一、什么是socket?    网络上的两个程序通过一个双向的通信连接实现的数据交换,这个连接的一端称为socket,socket通常也叫做"套接字",用来描述ip地址和端口,是一个通信连的句柄,可以实现不同虚拟机和计算机之间的通信。一般在...
    99+
    2023-01-31
    python
  • python学习(13)
    random.uniform(a,b)随机生成a,b之间的一个浮点数 random.uniform(1,20)1.0130916166719703 习题1:生成[“z1”,”y2”,”x3”,”w4”,”v5”] #coding...
    99+
    2023-01-31
    python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作