栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python代码优化案例分析

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)等都是同一个对象“”,没有必要进行值得比较。因为每一个类型只有一个类型对象。

  • 优化方式:

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/224287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号