Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何确定类实例的类型_Python_Python 3.x - Fatal编程技术网

Python 如何确定类实例的类型

Python 如何确定类实例的类型,python,python-3.x,Python,Python 3.x,要确定类别,我可以这样做: class A: pass a = A type(A) is type #True 或: 但是,在不知道类名的情况下,如何确定类实例的类型呢 大概是这样的: isinstance(a, a.__class__.__name__) #TypeError: isinstance() arg 2 must be a type or tuple of types 我找到了一个解决方案,但它不适用于Python 3x import types class A:

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

class A: pass    
a = A

type(A) is type #True
或:

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

大概是这样的:

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:

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

type(a)
是实例的类型,即它的类
a.。\uuuu class\uuuu
也是对实例类的引用,但您应该使用
type(a)


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

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

>>> isinstance(a, A)
True
您还可以通过调用
type()
来获取类,但这通常不是很有用:

>>> type(a)
<class '__main__.A'>
然而,从您的评论来看,您似乎想要确定对象是否是实例。如果你问这个问题,你会得到更好的答案

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

>>> import inspect
>>> inspect.isclass(a)
False
>>> inspect.isclass(A)
True
这是因为一切都是一个实例:

>>> isinstance(type, type)
True

但并不是所有的东西都是类。

你是在问如何确定一个对象是类还是类的实例吗?InstanceType是老式类,在3.x中不存在。@grifaton,我想区分类和实例。类和实例都是同样有效的对象,都有一个有意义的类型。区分“类和实例”没有多大意义——类也是实例,即元类的实例。元类也是类,它们本身也是某些类的实例(
type(type)是type
)。你为什么认为你需要这个?你为什么需要这个?可能有一个更好的解决方案,比你正在尝试的更好。类型(a)只适用于新样式的类!如果您使用的是旧样式的类,请查看是否可以将它们更改为新样式。否则,请使用.._类_,它也适用于旧样式@kindall的回答已经暗示了这一点,但我想我应该为人们更多地打开这个gotcha。
>>> import inspect
>>> inspect.isclass(a)
False
>>> inspect.isclass(A)
True
>>> isinstance(type, type)
True