确定变量是否为任何类的实例 [英] Determine if a variable is an instance of any class

查看:68
本文介绍了确定变量是否为任何类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定变量是否是Python 3中的实例?如果它具有 __ dict __ 属性,我认为它是一个实例.

How to determine if a variable is an instance in Python 3? I consider something to be an instance if it has __dict__ attribute.

示例:

is_instance_of_any_class(5)  # should return False
is_instance_of_any_class([2, 3])  # should return False

class A:
  pass

a = A()
is_instance_of_any_class(a)  # should return True

我已经看到有关使用 isinstance(x,type) inspect.isclass(x)的消息,但这对于类(A)来说为True,而不是实例.

I have seen messages about using isinstance(x, type) or inspect.isclass(x) but this would give True for the class (A), not the instance.

推荐答案

我认为您对此实例的理解是错误的,因为所有内容都是python中的对象,所以 5 是的对象类 int [2,3] 是类 list 的对象,依此类推.

I think your understanding of what an instance is wrong here, since everything is an object in python, so 5 is an object of class int and [2,3] is an object of class list and so on.

isinstance(x,y)是可行的方法,但是如果要检查 x 是内置类的对象还是您自己的自定义类,则应该使用 hasattr(x,'__dict __').

isinstance(x, y) is the way to go if you just want to check if x is an object of y, but if you want to check if x is an object of builtin class or your own custom defined class then you should be checking the existence of __dict__ using hasattr(x, '__dict__').

这篇关于确定变量是否为任何类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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