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

时间:2013-02-03 00:21:13

标签: python types

从这篇文章 - What's the canonical way to check for type in 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。

PS:这是一个出于好奇的问题,因为我从this book得到了这个例子,结果是真的,但我弄错了。我知道Duck打字是python中的首选方式。 (https://stackoverflow.com/a/154156/260127

ADDED

罗德里戈的回答对我有用。使用'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 个答案:

答案 0 :(得分:14)

您应该使用新式的课程:

class A(object):
    pass

即,从object派生。

问题是旧式对象的实现好像所有对象都是instance类型。

直接或间接从object派生将解决此问题。或者转到Python3,那里没有旧式的类。

答案 1 :(得分: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

答案 2 :(得分:7)

试试这个

print a.__class__ is A
True

答案 3 :(得分:2)

如果您定义a a = A(),则a是类A的实例。如果您只是执行a = A,则名称a指向类对象。

您可能需要A的实例,然后可以使用

进行测试
>>> a = A()
>>> isinstance(a, A)
True

新样式类将测试True type(A()) == A