装饰器不改变原函数名
修改最里层函数函数名,函数属性__name__
重新赋值
# encoding=utf8
def deco1():
def func1(func):
def func2(*args, **kwargs):
return func(*args, **kwargs)
func2.__name__ = func.__name__
return func2
return func1
def deco2():
def func1(func):
def func2(*args, **kwargs):
return func(*args, **kwargs)
return func2
return func1
@deco2()
def main(*args, **kwargs):
pass
print(main.__name__)
@deco1()
def main(*args, **kwargs):
pass
print(main.__name__)
>>> func2
>>> main
redis模块
2.9.1版本中,redis客户端有两个类,分别是StrictRedis
和Redis
,相同的方法入参的顺序和命名有些区别,需要特别注意。
StrictRedis
def lrem(self, name, count, value):
Redis
def lrem(self, name, value, num=0):
json解包float转str
当json串中有浮点型数据时,不能精确解包
import json
# json.__version__ = 1.9
j = '''{"float": 9.9}'''
print json.loads(j)
>>> {u'float': 9.9000000000000004}
可以通过设置json.loads
方法的parse_float
参数把浮点型数据转化为字符串
print json.loads(j, parse_float=lambda x: x)
>>> {u'float': '9.9'}
json.loads
函数中有说明,当parse_float != None
时,解码时会把浮点型转换为整形。类似的,当设置了parse_int
参数,也会做同样的预处理
print json.loads.__doc__
>>> ...
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
...
json.decoder.py
有以下转换
def JSONNumber(match, context):
match = JSONNumber.regex.match(match.string, *match.span())
integer, frac, exp = match.groups()
if frac or exp:
fn = getattr(context, 'parse_float', None) or float
res = fn(integer + (frac or '') + (exp or ''))
else:
fn = getattr(context, 'parse_int', None) or int
res = fn(integer)
return res, None
pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber)