The type function can be used to determine the object type. the sample code is as follows: 1. determine the object type.
You can use the type function to know the object type. the sample code is as follows:
x = 'Hello's = type(x)print sx = 'Hello's = type(x)print s
2. function overloading
When writing a function, you often encounter situations where you need to cope with different parameter types and different parameter quantities.
In C ++, multiple functions with different parameters of the same name are defined to be reloaded,
However, the overload in Python can be implemented using another method: parameter type judgment + default value
import os, sysdef tracelog(s='', n=40): if isinstance(n, int): print '-'*n else: print '-'*40 if isinstance(s, str): print s elif isinstance(s, list): s1 = '' for x in s: s1 = s1 + ' ' + x print s1 def main(): tracelog(n=50) tracelog(sys.argv) tracelog(n=20)
Main ()
import os, sys def tracelog(s='', n=40): if isinstance(n, int): print '-'*n else: print '-'*40 if isinstance(s, str): print s elif isinstance(s, list): s1 = '' for x in s: s1 = s1 + ' ' + x print s1 def main(): tracelog(n=50) tracelog(sys.argv) tracelog(n=20)main()
The code above defines a function tracelog, which prints out the s parameter. The s parameter can be a string or a list, and the horizontal line of the specified length can be printed.
Among them, the isinstance function is used to determine whether the object is of a specific type. The second parameter is the object type, which can be queried through the type function.