[英]How do I validate if the given input is an object in Python?
I am creating a validation function that would verify if the inputs are objects.我正在创建一个验证函数来验证输入是否为对象。
I have no idea how to approach this.我不知道如何处理这个问题。 So, any help or suggestion would be highly beneficial.因此,任何帮助或建议都是非常有益的。
Any search for object validation leads me to form validation in Django and that's not what I am looking for.任何对对象验证的搜索都会让我在 Django 中进行表单验证,这不是我要找的。
Assuming that you meant to validate objects of user created classes(because otherwise everything in python is an object), tried in Python3:假设您打算验证用户创建的类的对象(因为否则 python 中的所有内容都是对象),在 Python3 中尝试:
import inspect
def is_object(x):
if isinstance(x, (int, str, float, complex)):
print("Built-in class's object")
return False
elif hasattr(x, '__class__') and inspect.isclass(x) is False:
print("Custom class's object")
return True
elif inspect.isclass(x):
print("Class")
return False
else:
return False
You can use type()
to validate given input.您可以使用type()
来验证给定的输入。
>>> a= 10
>>> type(a)
<class 'int'>
>>> class custom:
pass
>>> a=custom()
>>> type(a)
<class '__main__.custom'>
>>>a="hello"
>>> type(a)
<class 'str'>
>>>a=[]
>>>type(a)
<class 'list'>
or else you can use isinstance()
method.否则你可以使用isinstance()
方法。
>>>a=[]
>>>isinstance(a,list)
True
>>> a="hello"
>>>isinstance(a,str)
True
>>>a=122
>>>isinstance(a,str)
False
>>>a=122
>>>isinstance(a,float)
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.