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

Python object type judgment and function overloading

高洛峰
Release: 2016-10-19 14:57:29
Original
1377 people have browsed it

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
Copy after login

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)
Copy after login

​​​

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()
Copy after login

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.


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template