第一版举例:
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,如需转载请自行联系原作者