如何检查变量的类型?蟒蛇

Pol*_*Pol 5 python variables

我需要做一件事,如果args是整数和ather的东西,如果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()
Run Code Online (Sandbox Code Playgroud)

Joc*_*zel 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()
Run Code Online (Sandbox Code Playgroud)

它的用途types.StringTypes是因为Python实际上有两种字符串:unicode和bytestrings - 这种方式都有效.

在Python3中,内置类型已从typeslib中删除,并且只有一种字符串类型.这意味着类型检查看起来像isinstance(s, int)isinstance(s, str).

  • 实际上测试`basestring`(`str`和`unicode`的超类)而不是`types.StringTypes`应该也可以. (2认同)