前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python代码优化案例分析

python代码优化案例分析

作者头像
py3study
发布2020-01-07 11:12:59
4230
发布2020-01-07 11:12:59
举报
文章被收录于专栏:python3python3

第一版举例:

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)...

摘选自《python核心编程(第二版)》第四章P68

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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