码迷,mamicode.com
首页 > 编程语言 > 详细

python 双层装饰器、格式化、模块、迭代器和生成器

时间:2016-06-10 19:00:37      阅读:472      评论:0      收藏:0      [点我收藏+]

标签:

一、双层装饰器

一、双层装饰器


#!/usr/bin/env python
# -*- coding:utf-8 -*-
USER_INFO={}
#USER_INFO[‘is_login‘] = True
#USER_INFO[‘user_type‘] = 2

def check_login(func):
    def inner(*args ,**kwargs):
        if USER_INFO.get(‘is_login‘,None):
            ret = func(*args,**kwargs)
            return  ret
        else:
            print(‘请登录‘)
    return  inner
def check_admin(func):
    def inner(*args ,**kwargs):
        if USER_INFO.get(‘user_type‘,None)==2:
            ret = func(*args,**kwargs)
            return  ret
        else:
            print(‘无权查看‘)
    return  inner
@check_login
@check_admin
def index():
    print("index")
index()

#号的函数分别打开执行代码

以下为执行结果:
请登录
无权查看
index
 

二、格式化

1.%s %d

#常用格式化:

tpl = "i am %s" % "alex"
print(tpl)
以下为执行结果:
i am alex

tpl = "i am %s age %d" % ("alex", 18)
print(tpl)
以下为执行结果:
i am alex age 18

tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}
print(tpl)
以下为执行结果:
i am alex age 18

tpl = "percent %.2f" % 99.97623
print(tpl)
以下为执行结果:
percent 99.98

tpl = "i am %(pp).2f" % {"pp": 123.425556, }
print(tpl)
以下为执行结果:
i am 123.43

tpl = "i am %.2f %%" % 123.425556
print(tpl)
以下为执行结果:
i am 123.43 %

2.format

#常用格式化:
tpl = "i am {}, age {}, {}".format("seven", 18, ‘alex‘)
print(tpl)
以下为执行结果:
i am seven, age 18, alex

tpl = "i am {}, age {}, {}".format(*["seven", 18, ‘alex‘])
print(tpl)
以下为执行结果:
i am seven, age 18, alex

tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
print(tpl)
以下为执行结果:
i am seven, age 18, really seven

tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
print(tpl)
以下为执行结果:
i am seven, age 18, really seven

tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
print(tpl)
以下为执行结果:
i am seven, age 18, really seven

tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
print(tpl)
以下为执行结果:i am seven, age 18, really seven
i am seven, age 18, really seven

tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
print(tpl)
以下为执行结果:
i am 1, age 2, really 3

tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
print(tpl)
以下为执行结果:
i am seven, age 18, money 88888.100000

tpl = "i am {:s}, age {:d}".format(*["seven", 18])
print(tpl)
以下为执行结果:
i am seven, age 18

tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
print(tpl)
以下为执行结果:
i am seven, age 18

tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
print(tpl)
以下为执行结果:
i am seven, age 18

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
print(tpl)
以下为执行结果:
numbers: 1111,17,15,f,F, 1587.623000%

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
print(tpl)
以下为执行结果:
numbers: 1111,17,15,f,F, 1587.623000%

tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
print(tpl)
以下为执行结果:
numbers: 1111,17,15,f,F, 1500.000000%

tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
print(tpl)
以下为执行结果:
numbers: 1111,17,15,f,F, 1500.000000%
 

三、迭代器生成器

def func():
print(‘start‘)
print(‘11111111‘)
yield 1
print(‘2222222222222‘)
yield 2
print("33333333333333")
yield 3
print("4444444444")
yield ("aaaaaaaa")ret = func()
print(ret)
# for i in ret:
#     print(i)
r1 = ret.__next__() #进入函数找到yileld,获取yield后面的数据。
print(r1)
r2 = ret.__next__() #进入函数找到yileld,获取yield后面的数据。
print(r2)
r3 = ret.__next__() #进入函数找到yileld,获取yield后面的数据。
print(r3)
r4 = ret.__next__() #进入函数找到yileld,获取yield后面的数据。
print(r4)
以下为执行结果:
start
11111111
1
2222222222222
2
33333333333333
3
4444444444
aaaaaaaa

while循环生成迭代器

def myrange(arg):
    start=0
    while True:
        yield start
        start+=1
ret =myrange(3)
r = ret.__next__()
print (r)
r = ret.__next__()
print (r)
r = ret.__next__()
print (r)
r = ret.__next__()
print (r)
以下为执行结果:
0
1
2
3

递归

def func(n):
    n +=1
    if n >=10:
        return ‘end‘
    print (n)
    return  func(n)
r = func(1)
print(r)
以下为执行结果:
2
3
4
5
6
7
8
9
end
 

四、模块

 

json

将字符串转换成基本数据类型

 import  json
    dic = {‘k1‘:"v1"}
    #将字典转换成字符串
    result = json.dumps(dic)
    print ("result",type(result))

#将字符串转换成基本数据类型
s1 = ‘{"k1":123}‘
dic = json.loads(s1)
print  ("dic",type(dic))

import requests
response = requests.get(‘http://wthrcdn.etouch.cn/weather_mini?city=北京‘)
response.encoding=‘utf-8‘
dic = json.loads(response.text)
print(dic)
以下为执行结果:
result <class ‘str‘>
dic <class ‘dict‘>
{‘data‘: {‘wendu‘: ‘24‘, ‘forecast‘: [{‘date‘: ‘10日星期五‘, ‘high‘: ‘高温 31℃‘, ‘type‘: ‘雷阵雨‘, ‘low‘: ‘低温 20℃‘, ‘fengli‘: ‘3-4级‘, ‘fengxiang‘: ‘北风‘}, {‘date‘: ‘11日星期六‘, ‘high‘: ‘高温 30℃‘, ‘type‘: ‘多云‘, ‘low‘: ‘低温 19℃‘, ‘fengli‘: ‘微风级‘, ‘fengxiang‘: ‘无持续风向‘}, {‘date‘: ‘12日星期天‘, ‘high‘: ‘高温 32℃‘, ‘type‘: ‘晴‘, ‘low‘: ‘低温 21℃‘, ‘fengli‘: ‘微风级‘, ‘fengxiang‘: ‘无持续风向‘}, {‘date‘: ‘13日星期一‘, ‘high‘: ‘高温 27℃‘, ‘type‘: ‘雷阵雨‘, ‘low‘: ‘低温 18℃‘, ‘fengli‘: ‘微风级‘, ‘fengxiang‘: ‘无持续风向‘}, {‘date‘: ‘14日星期二‘, ‘high‘: ‘高温 26℃‘, ‘type‘: ‘阵雨‘, ‘low‘: ‘低温 17℃‘, ‘fengli‘: ‘微风级‘, ‘fengxiang‘: ‘无持续风向‘}], ‘ganmao‘: ‘各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。‘, ‘city‘: ‘北京‘, ‘yesterday‘: {‘date‘: ‘9日星期四‘, ‘high‘: ‘高温 32℃‘, ‘type‘: ‘阴‘, ‘low‘: ‘低温 22℃‘, ‘fx‘: ‘南风‘, ‘fl‘: ‘3-4级‘}, ‘aqi‘: ‘120‘}, ‘status‘: 1000, ‘desc‘: ‘OK‘}

python基本数据类型转换字符串

import json
#python基本数据类型转换字符串
r =json.dumps([11,22,33])
li="[‘alex‘,‘eric‘]"
ret = json.load(li) #通过load反序列话,一定要用双引号。
print (ret,type(ret))
import json
#python基本数据类型转换字符串
r =json.dumps([11,22,33])
li="[‘alex‘,‘eric‘]"
ret = json.load(li) #通过load反序列话,一定要用双引号。
print (ret,type(ret))
 

pickle

import  pickle     #jsonzhi只能支持 基本的数据类型,pickle支持任何类型
li = [11,22,33]
r = pickle.dumps(li)
print(r)
result =pickle.loads(r)
print(result)

pickle.dump(li,open(‘db‘,‘wb‘))

r=pickle.load(open(‘db‘,‘rb‘))
print (r)
以下为执行结果
b‘\x80\x03]q\x00(K\x0bK\x16K!e.‘
[11, 22, 33]
[11, 22, 33]
 

time

import time

print (time.time())  #1970 uninx
以下为执行结果:
1465551477.927157

print (time.ctime())
以下为执行结果:
Fri Jun 10 17:37:57 2016

print (time.ctime(time.time()-86640))
以下为执行结果:
Thu Jun  9 17:33:57 2016

time_obj = time.gmtime()
print (time_obj)
以下为执行结果:
time.struct_time(tm_year=2016, tm_mon=6, tm_mday=10, tm_hour=9, tm_min=37, tm_sec=57, tm_wday=4, tm_yday=162, tm_isdst=0)

print ("{year}-{month}".format(year=time_obj.tm_year,month=time_obj.tm_mon))
以下为执行结果:
2016-6

print(time.localtime())
以下为执行结果:
time.struct_time(tm_year=2016, tm_mon=6, tm_mday=10, tm_hour=17, tm_min=37, tm_sec=57, tm_wday=4, tm_yday=162, tm_isdst=0)

print(time.mktime(time.localtime())) #转换成时间戳
以下为执行结果:
1465551477.0

tm=time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())
print(tm)
以下为执行结果
2016-06-10 09:37:57

print(time.strptime("2016-05-6 10:15","%Y-%m-%d %H:%M"))
以下为执行结果:
time.struct_time(tm_year=2016, tm_mon=5, tm_mday=6, tm_hour=10, tm_min=15, tm_sec=0, tm_wday=4, tm_yday=127, tm_isdst=-1)
 

datetime

import datetime
print(datetime.date.today())
以下为执行结果:
2016-06-10

print(datetime.datetime.now())
以下为执行结果:
2016-06-10 17:44:50.304135

print(datetime.datetime.now() -datetime.timedelta(hours=10))
以下为执行结果:
2016-06-10 07:44:50.304135

print(datetime.datetime.now().replace(1988,10,18))
以下为执行结果:
1988-10-18 17:44:50.304135

str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
print(str_to_date)
以下为执行结果:
2006-11-21 16:30:00

python 双层装饰器、格式化、模块、迭代器和生成器

标签:

原文地址:http://www.cnblogs.com/wudalang/p/5573776.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!