First edition Example:
def displaynumtype (num): Print num, "is", if Type (num) ==type (0): print ' An Interger ' elif type (num) ==type (0 L): 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!! '
Final Version Example:
def displaynumtype (num): Print num, ' is ', if Isinstance (num, (Int,long,float,complex)): print ' A number of Typ E: ', type (num). __name__ else:print ' not a number at all!! '
Optimization ideas:
1. Reduce the number of function calls
In the first version of the code, the two-time type () is called each time it is judged.
Import typesif type (num) ==types. Inttype ...
2. Compare object value VS object identity
The type (0), type (42), and so on are the same object "<type ' Int ' >", and there is no need to compare it. Because each type has only one type of object.
If Type (num) is types. Inttype. # #or Type (0)
3. Reduce the number of queries
In order to get the object type of an integer, the interpreter had to find the name of the types module first, and then find the inttype in the dictionary of the module.
By using From-import, you can reduce the query one time.
From types import inttypeif type (num) is Inttype
4. Conventions and code styles
The Isinstance () function makes the IF statement more convenient and more readable.
If Isinstance (num,int) ...
Selected from "Python Core programming (second Edition)", chapter fourth P68
Python Code optimization Case study