前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python学习(day4)

python学习(day4)

作者头像
py3study
发布2020-01-10 10:58:29
2450
发布2020-01-10 10:58:29
举报
文章被收录于专栏:python3python3

1、装饰器:

代码语言:javascript
复制
'''
实现装饰器只是储备:
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()
代码语言:javascript
复制
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、迭代器:

代码语言:javascript
复制
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、生成器:

代码语言:javascript
复制
'''
生成器 :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、斐波那契数列:

代码语言:javascript
复制
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、匿名函数:

代码语言:javascript
复制
calc = lambda x:x*3
print(calc(3))

6、列表生成式:

代码语言:javascript
复制
#列表生成式:
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、内置方法:

代码语言:javascript
复制
#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、软件目录结构规范:

代码语言:javascript
复制
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: 项目说明文件。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档