如果 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/