python最佳实践

这段时间开始研究Python了在日常工作中总结了以下的实践:
if retrun while 中不用使用()(括号)
运算中使用()

(1<<2)&5

设置整数型浮点使用

7.0

方法名小写,类名首字母大写
def funciton:
class Function:

别使用build-in的关键字 例如不要使用
list=[1,2,3] dict={'name':'xiaoli'}
使用in keys()

if x in dict.keys():

通常不要使用可变量作为默认值可以使用一下方式
使用 is 判断None

def test(x,de_x=None):
    if de_x is None:
        de_x=[]

可以的话尽量使用迭代方法:

for key, val in mapping.iteritems(): ...

性能分析:

python -m profile -o stats myscript.py

import pstats
p = pstats.Stats('stats')
p.sort_stats('time').print_stats(15) #按执行时长排序

转换编码

-*- coding: UTF-8 -*-
#循环
while True
    xxx
    if yyy: break
#交换
a=5
b=3
a,b=b,a
#同一赋值

#bad
a=5
b=5
c=5
#good
a=b=c=5
if x == 1: y = fun1(x)
elif x == 2: y = fun2(x)
elif x == 3: y = fun3(x)
else: y = None 
#可以使用字典形式的方法:
funs = {1: fun1, 2: fun2, 3: fun3}
y = funs.get(x, lambda x:None)(x)

#拼接字符串
sl = ["ab", "cd", "ef"]
all = "".join(sl)

#使用列表推导式
vals = [2, 3, -5, 0]
result = [el * el for el in vals if el > 0]

#私有变量用_标注 
class Foo(object):
    def __init__(self, x, y, z):
        self.x_public = x
        self._y_private = y
        self.__z_veryprivate = z
print (Foo(1, 2, 3).x_public)

#从-2开始叠加
vals = [5, 7 ,8]
tot = sum(vals, -2.0) #tot=18

#反转list等
alist[::-1]


#判别类型
if isinstance(s, basestring): ...
if isinstance(seq, (list, tuple)): ...
if hasattr(seq, "__getitem__"): ...

#使用d=dict()会去先load dict()方法
d=[]
d={} 

# return a.sort() 会先去load() sort()方法
a.sort()
retrun a 

#不用a<b<c<d
a<b and b<c and c<d 

#不用 a!=2 不用a is not 2
if not a is 2:

#不用if not a 不用if len(a) 拒绝 if a==[] (when a is list)
if a

#不用 if a is None /if a is not None (a是对象时)
if not a

#不用for i in range(len(list)) 
for x,y in enumerate(list) 

#不用return str((a*(b+c)))
return "%s" % (a*(b+c))  

#不用return sum(i for i in range(50000))
for i in range(50000):
        s += i
    return s

#不用for i in range(1000):
#        l.append(i)
#    return l
return [i for i in range(1000)]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值