python代码优化案例分析

第一版举例:

1
2
3
4
5
6
7
8
9
10
11
12
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!!'

最终版举例:

1
2
3
4
5
6
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()。

  • 优化方式:

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


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

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

  • 优化方式:

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


3、减少查询次数

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

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

  • 优化方式:

1
2
from  types  import  IntType
if  type (num)  is  IntType


4、惯例和代码风格

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

  • 优化方式:

1
if  isinstance (num, int )...


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











本文转自Grodd51CTO博客,原文链接:http://blog.51cto.com/juispan/2050529,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值