2010-08-09 74 views
5

如果args是整数,我需要做一件事,如果args是字符串,则需要做一件事。如何检查变量的类型? Python

我该如何检查类型?例如:

def handle(self, *args, **options): 

     if not args: 
      do_something() 
     elif args is integer: 
      do_some_ather_thing: 
     elif args is string: 
      do_totally_different_thing() 

回答

13

首先,*args总是一个列表。你想检查它的内容是否是字符串?

import types 
def handle(self, *args, **options): 
    if not args: 
     do_something() 
    # check if everything in args is a Int 
    elif all(isinstance(s, types.IntType) for s in args): 
     do_some_ather_thing() 
    # as before with strings 
    elif all(isinstance(s, types.StringTypes) for s in args): 
     do_totally_different_thing() 

它采用types.StringTypes因为Python实际上有两种字符串:Unicode和字节串 - 这样既工作。

在Python3中,内建类型已从types库中删除,并且只有一个字符串类型。 这意味着类型检查看起来像isinstance(s, int)isinstance(s, str)

+0

你的权利。是一览。 – Pol 2010-08-09 14:30:41

+0

是否有任何使用'isinstance(s,types.IntType)'而不是'isinstance(s,int)'的偏好呢?还是仅仅为了与你提到的两种类型的字符串一致?只是好奇。 – 2010-08-09 14:35:31

+1

您的解决方案与python 3.1不兼容! – banx 2010-08-09 14:37:11

0
type(variable_name) 

然后,你需要使用:

if type(args) is type(0): 
    blabla 

上面,我们比较如果变量参数的个数类型是一样的文字0这是一个整数,如果你想知道例如类型是否长,您与type(0l)等比较。

+0

我不明白。 如何使用它? – Pol 2010-08-09 14:28:18

+4

呃。 'type(2)'是'int',但无论如何,'type'是不好的Python – katrielalex 2010-08-09 14:29:41

0

如果您知道您期待的是整数/字符串参数,则不应该将其吞入*args。不要

def handle(self, first_arg = None, *args, **kwargs): 
    if isinstance(first_arg, int): 
     thing_one() 
    elif isinstance(first_arg, str): 
     thing_two() 
1

你也可以尝试做一个更Python的方式,而不使用typeisinstance(首选,因为它支持继承):

if not args: 
    do_something() 
else: 
    try: 
     do_some_other_thing() 
    except TypeError: 
     do_totally_different_thing() 

这显然取决于什么呢do_some_other_thing()

0

没有人提到这个问题,但更容易请求原谅的原则可能适用,因为我相信你会做一些与该整数:

def handle(self, *args, **kwargs): 
    try: 
     #Do some integer thing 
    except TypeError: 
     #Do some string thing 

当然,如果该整数事情是修改值在你的名单中,也许你应该先检查。当然,如果你想通过args循环,并做一些对整数和别的字符串:

def handle(self, *args, **kwargs): 
    for arg in args: 
     try: 
      #Do some integer thing 
     except TypeError: 
      #Do some string thing 

当然这也假设在尝试任何其他操作将抛出一个TypeError。

+0

其实我已经提到它:) – systempuntoout 2010-08-09 14:45:03