Python中的用户定义类型检查:“type(A()) is A”返回false

9 投票
4 回答
3485 浏览
提问于 2025-04-17 14:34

在这篇帖子中 - 在Python中检查类型的标准方法是什么?,我可以用这段代码来检查对象o是否是字符串类型。

o = "str"; print type(o) is str --> True

不过,对于用户自定义的类型,type(a) is A似乎不太管用。

class A:
    def hello(self):
        print "A.hello"
a = A()

print type(a) is A # --> False
print type(a) == A # --> False

这是为什么呢?我该如何正确检查用户自定义类型的类型呢?我在Mac OS X上使用的是Python 2.7。

附注:这个问题出于好奇,因为我从这本书中得到了这个例子,期望结果是true,但我得到了false。我知道在Python中,鸭子类型是更受欢迎的方式。(https://stackoverflow.com/a/154156/260127)

补充

rodrigo的回答对我有用。使用'isinstance'并不能给我确切的类型,它只是测试一个对象是否是某个类或其子类的实例。

class C(A):
    def hello(self):
        print "C.hello"

a = A()
c = C()

print isinstance(a, A) --> True
print isinstance(c, A) --> True
print isinstance(a, C) --> False
print isinstance(c, C) --> True
print "----"
print type(a) == A --> True
print type(c) == A --> False

补充 2

jdurango的回答(a.__class__ is A)让我想到了一个有趣的Java等价方式。

a.getClass() == A.class <--> a.__class__ == A (a.__class__ is A)
a isinstance A <--> isinstance(a, A)
c isinstance A <--> isinstance(c, A)

我不知道哪个是抄哪个。

4 个回答

7

为什么不使用 isinstance(instance, class) 呢?

>>> class A:
...     def hello(self):
...        print "A.hello"
... 
>>> type(A)
<type 'classobj'>
>>> a = A()
>>> type(a)
<type 'instance'>
>>> isinstance(a, A)
True
7

试试这个

print a.__class__ is A
True
14

你应该使用新的类样式:

class A(object):
    pass

也就是说,要从 object 这个基础类派生。

问题在于,旧式类的对象就像都是 instance 类型一样被实现。

直接或间接地从 object 派生可以解决这个问题。或者你可以直接使用Python3,那里就没有旧式类了。

撰写回答