为了确定类别,我可以这样做:
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:
你的问题有点不清楚。您想确定“类实例的类型”。这可能意味着两件事。您要确定的是实例是特定类的实例。你可以这样做:
您还可以使用
type()
调用获取类,但这通常不是很有用:但你所做的测试并不能证明这一点。相反,他们检查类是什么类型。但是Python 3只有一种类型的类。Python 2以及“旧样式”和“新样式”类,但是Python 3只有新样式的类,所以没有必要在python3中进行这种检查。
你也可以使用元类。在这种情况下,可以通过检查类的
__class__
来找到元类:但是,从您的注释来看,您似乎想确定对象是否是实例。如果你问的话你会得到更好的答案。。。
无论如何,要做到这一点,您可以使用
inspect.isclass
:这是因为一切都是一个实例:
但并不是所有的东西都是一门课。
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,因此它不再存在。
相关问题 更多 >
编程相关推荐