1. Determine the object type
You can know the type of the object through the type function. The sample code is as follows:
x = 'Hello' s = type(x) print s x = 'Hello' s = type(x) print s
2. Function overloading
When writing functions, we often encounter the need to deal with different parameter types and case of different number of parameters.
In C++, multiple functions with the same name but different parameters are usually defined to achieve overloading.
But overloading in Python can be achieved by another method: parameter type judgment + default value
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( )
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 above code defines a function tracelog. This function will print out the s parameter. The s parameter can be a string or a list, and it can also print a horizontal line of a specified length
Among them: isinstance function It is a function used to determine whether an object is of a specific type. The second parameter is the object type, which can be queried through the type function.