Python-OOP中类实例的奇怪类型信息

2024-06-16 12:27:31 发布

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

我正在尝试确定对象的类型信息。你知道吗

>>> class Class1: pass

>>> obj1=Class1()
>>> type(obj1)
<type 'instance'>

我期望type(obj1)返回'Class1'。为什么它是'instance'?什么类型'instance'?你知道吗


Tags: 对象instance类型typepassclassclass1类型信息
2条回答

在Python2中,如果一个类没有从object(直接或间接)继承,那么它将被视为一个旧式类。在旧式类中,所有实例都是'instance'类型。你知道吗

docs

The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always <type 'instance'>.

将类更改为从object继承以使其成为新样式的类:

class Class1(object): pass

演示:

>>> class Class1(object): pass

>>> type(Class1())
<class '__main__.Class1'>

这是python2.x中new-style and classic classes之间的区别之一。事实上:

The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always <type 'instance'>.

您必须使用新的样式类,通过从object继承来获得预期的type()结果。你知道吗

>>> class C1: pass
...
>>> class C2(object): pass
...
>>> type(C1())
<type 'instance'>
>>> type(C2())
<class '__main__.C2'>

相关问题 更多 >