如何确定类实例的类型

2024-09-29 01:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

为了确定类别,我可以这样做:

class A: pass    
a = A

type(A) is type #True

或:

import inspect
inspect.isclass(A) 

但是如何在不知道类名的情况下确定类实例的类型呢?

像这样的:

isinstance(a, a.__class__.__name__)
#TypeError: isinstance() arg 2 must be a type or tuple of types

我找到了一个解决方案,但它不适用于Python 3x

import types

class A: pass
a = A()

print(type(a) == types.InstanceType)
#AttributeError: 'module' object has no attribute 'InstanceType'

解决方案:

if '__dict__' in dir(a) and type(a) is not type:

Tags: importtrueistype情况pass解决方案类别
3条回答

你的问题有点不清楚。您想确定“类实例的类型”。这可能意味着两件事。您要确定的是实例是特定类的实例。你可以这样做:

>>> isinstance(a, A)
True

您还可以使用type()调用获取类,但这通常不是很有用:

>>> type(a)
<class '__main__.A'>

但你所做的测试并不能证明这一点。相反,他们检查是什么类型。但是Python 3只有一种类型的类。Python 2以及“旧样式”和“新样式”类,但是Python 3只有新样式的类,所以没有必要在python3中进行这种检查。

你也可以使用元类。在这种情况下,可以通过检查类的__class__来找到元类:

>>> from abc import ABCMeta
>>> class B(metaclass=ABCMeta): pass
>>> type(B)
<class 'abc.ABCMeta'>

但是,从您的注释来看,您似乎想确定对象是否是实例。如果你问的话你会得到更好的答案。。。

无论如何,要做到这一点,您可以使用inspect.isclass

>>> import inspect
>>> inspect.isclass(a)
False
>>> inspect.isclass(A)
True

这是因为一切都是一个实例:

>>> isinstance(type, type)
True

但并不是所有的东西都是一门课。

type(a)是实例的类型,即其类。a.__class__也是对实例类的引用,但是应该使用type(a)

types.InstanceType仅适用于Python pre-3.0版本中的旧样式类,其中所有实例都具有相同的类型。您应该在2.x中使用新样式的类(派生自object)。在Python 3.0中,所有类都是新样式的类。

这是因为旧样式的类实例都是InstanceType,在Python3.x中只有与类型相同的新样式类。因此,在Python3.x中,a将是a类型,因此不需要包含InstanceType,因此它不再存在。

相关问题 更多 >