Home >Backend Development >Python Tutorial >Python object type judgment and function overloading

Python object type judgment and function overloading

高洛峰
高洛峰Original
2016-10-19 14:57:291376browse

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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn