Python object type judgment and function overloading

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.