简体   繁体   English

如何验证给定的输入是否是 Python 中的对象?

[英]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.

相关问题 如何验证python中的字符串和整数输入? - How do I validate both a string and an integer input in python? 如何在python中验证用户输入是字母还是空格? - How do I validate that user input is alphabetic or spaces in python? Python:如何找到给定输入的方程式值 - Python: How do i find an equation's value for a given input 如何在Python中验证用户输入是否既是浮点数又是给定范围的? - How to validate if a user input is both a float and with a given range in Python? 给定日期对象在python中,我怎么减去一天 - given a date object in python, how do I subtract one day 如何验证python中的条目小部件? - How do I validate an entry widget in python? 如何找到实例化的 Python class object 的输入参数? - How do I find the input parameters of an instantiated Python class object? 在Python / Django中,在给定该对象作为父类的情况下,如何检查该对象是否为X的子类? - In Python/Django, how do I check if an object is a subclass of X given that object as a parent class? 如何检查用户给定输入的字符串是否等于 Python 中的某个字母/单词 - How do I check if a string with a user given input is equal to a certain letter/ word in Python 如何验证以2开头的用户输入? - How do i validate user input that starts with 2 numbers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM