为了账号安全,请及时绑定邮箱和手机立即绑定

python代码优化案例分析

标签:
Python

第一版举例:

def displayNumType(num):
    print num,"is",
    if type(num)==type(0):
        print 'an interger'
    elif type(num)==type(0L):
        print 'a long'
    elif type(num)==type(0.0):
        print 'a float'
    elif type(num)==type(0+0j):
        print 'a complex number'
    else:
        print 'not a number at all!!'

最终版举例:

def displayNumType(num):
    print num,'is',
    if isinstance(num,(int,long,float,complex)):
        print 'a  number of type:',type(num).__name__
    else:
        print 'not a number at all!!'

优化思路:

1、减少函数调用的次数

在第一版代码中,每次判断会调用两次type()。

  • 优化方式:

import types
if type(num)==types.IntType...

2、对象值比较 VS 对象身份比较

type(0),type(42)等都是同一个对象“<type 'Int'>”,没有必要进行值得比较。因为每一个类型只有一个类型对象。

  • 优化方式:

if type(num) is types.IntType...  ##or type(0)

3、减少查询次数

为了得到整数的对象类型,解释器不得不首先查找types这个模块的名字,然后在该模块的字典中查找IntType。

通过使用from-import,可以减少一次查询。

  • 优化方式:

from types import IntType
if type(num) is IntType

4、惯例和代码风格

isinstance()函数让if语句更方便,并具有更好的可读性。

  • 优化方式:

if isinstance(num,int)...

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消