在Python中使用函数参数验证数据类型 [英] Verify the datatype with function argument in Python

查看:406
本文介绍了在Python中使用函数参数验证数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个函数,它使用if-else语句和python的类型函数来验证函数参数是(list,tuple,dictionary和string)数据类型的类型,但问题是当我将参数作为列表给出时并设置匹配完美,但当我给元组或字符串或字典它给出错误我没有得到它因为我是初学者所以需要帮助



我尝试过:



 def any(arg):
如果type(arg)== list :
print'yes it \'a list element:{}'。format(arg)
elif type(arg)== set:
print'这是一个集:{} '.format(arg)
#elif type(arg)== dict(arg):
#print'这是一个字典元素{}:{}'。format()
elif type(arg)== tuple:
print'this is a tuple:{}'。format(arg)
elif type(arg)== str:
print'这是一个字符串:{}'。格式(arg)
else:
print('格式无效')

#anything(arg = {'arg':'ashish'})#NOT WORKING
任何东西(arg = ['ashish'])
任何东西(arg = {'set'})
任何东西(arg =('tuple'))#HERE TUPLE也提供类型字符串如何?
any(arg ='string')

 

解决方案

这似乎在Python 3下工作,我建议你升级。另请参阅 3。数据模型 - Python 3.4.9文档 [ ^ ]。

I've defined one function which verifies that function argument is (list, tuple, dictionary and string) type of datatype using if-else statement and type function of python, but the problem is when i'm giving argument as list and set it matched perfectly but when i give tuple or string or dictionary it give error i'm not getting it beacause i'm a beginner so help needed

What I have tried:

def anything(arg):
        if type(arg) == list:
            print 'yes it\'s a list element : {}'.format(arg)
        elif type(arg) == set:
            print 'this is a set: {}'.format(arg)
        # elif type(arg) == dict(arg):
        #     print 'this is a dictionary element {}: {}'.format()
        elif type(arg) == tuple:
            print 'this is a tuple: {}'.format(arg)
        elif type(arg) == str:
            print 'this is a string: {}'.format(arg)
        else:
            print ('Invalid format')

# anything(arg = {'arg' : 'ashish'}) #NOT WORKING
anything(arg = ['ashish'])
anything(arg = {'set'})
anything(arg = ('tuple')) #HERE TUPLE ALSO PROVIDE TYPE STRING HOW??
anything(arg = 'string') 

解决方案

This appears to work under Python 3, I suggest you upgrade. Also see 3. Data model — Python 3.4.9 documentation[^].


这篇关于在Python中使用函数参数验证数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆