我需要做一件事,如果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中,内置类型已从types
lib中删除,并且只有一种字符串类型.这意味着类型检查看起来像isinstance(s, int)
和isinstance(s, str)
.