如何检查变量类型?Python

5 投票
5 回答
7501 浏览
提问于 2025-04-16 02:32

我需要做一件事,如果 args 是整数;如果 args 是字符串,则做另一件事。

我该如何检查类型呢?举个例子:

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()

5 个回答

0
type(variable_name)

那么你需要使用:

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

上面我们在比较变量 args 的类型是否和数字 0 的类型一样,0 是一个整数。如果你想知道某个类型是不是长整型(long),你可以用 type(0l) 来比较,等等。

1

你也可以尝试用更符合Python风格的方法来做,而不使用 typeisinstance(这样做更好,因为它支持继承):

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

这显然取决于 do_some_other_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)

撰写回答