简体   繁体   中英

Checking the type of parameter entered into a function

So I want to create a function and have it perform differently based on the type of the parameter passed in. Specifically I want it to do one thing if a string is entered, and something else if a list is entered. Is this possible in Python? And if so how would I go about doing it?

At the moment I've tried using isinstance() but it doesn't seem to be hitting any of my if statements:

def tester(*args):
    if (isinstance(args, str)):
        return "String"
    elif (isinstance(args, list)):
        return"List"
    else:
        return "You dun goofed"

EDIT: The user will only ever be passing in one argument at a time, either a list or a string.

*args is the tuple of arguments passed to the argument. The splat ( * ) operator unpacks the arguments given in the function call eg.

>>> def tester(*args):
        print args
        print type(args)


>>> tester(1, 'a')
(1, 'a')
<type 'tuple'>

So what you probably want to do is check isinstance on each of the args and make sure they are all str or list for example:

if all(isinstance(a, str) for a in args):

Looks like all you would be passing is a single argument to your function. In that case remove the '*' since it is always considered as a tuple of arguments. It is variable-length arguments and is to be used when you aren't sure of the number of arguments that you function would need.

def tester(args):
    if (isinstance(args, str)):
        return "String"
    elif (isinstance(args, list)):
        return"List"
    else:
        return "You dun goofed"

If your function actually requires variable length parameters and you want to check whether the first parameter being passed is a string or a list, you can do:

def tester(*args):
    if (isinstance(args[0], str)):
        return "String"
    elif (isinstance(args[0], list)):
        return"List"
    else:
        return "You dun goofed"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM