python - 如何检查变量类型? Python

标签 python variables

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

最佳答案

首先,*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 和 bytestrings - 这种方式都有效。

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

关于python - 如何检查变量类型? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3440969/

相关文章:

java - 最终静态变量及其使用

PHP 变量作用域

python - 如何在python中左移一个位数组

python - 子集 Pandas DataFrame 二级索引和重新分配值

python - 无法解析包含表格数据(iframe)的网站中的元素

javascript - 分配 html 表单输入一个 JS 变量

linux - 从另一个变量的内容中获取变量的内容,两个变量名称具有相同的尾随数字

实例化后可从方法访问的 Javascript 局部变量?

python - Django 从 JSON 数据创建一个 QueryDict

python - 我正在尝试获取当前在 Windows 7 上使用 Python 运行的所有进程和应用程序