From this post - What's the canonical way to check for type in Python?, I could use this code to check object o is string type.
o = "str"; print type(o) is str --> True
However, with user defined type, type(a) is A
doesn't seem to work.
class A:
def hello(self):
print "A.hello"
a = A()
print type(a) is A # --> False
print type(a) == A # --> False
Why is this? How can I get the correct type checking for user defined type? I use python 2.7 on Mac OS X.
PS: This is a question out of curiosity, as I got this example from this book to get true as a result, but I got false. I understand that Duck typing is a preferred way in python. (https://stackoverflow.com/a/154156/260127)
rodrigo's answer works for me. Using 'isinstance' doesn't give me an exact type, it just tests if an object is an instance of a class or a subclass.
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
jdurango's answer (a.__class__ is A
) gave me pretty interesting Java equivalent.
a.getClass() == A.class <--> a.__class__ == A (a.__class__ is A)
a isinstance A <--> isinstance(a, A)
c isinstance A <--> isinstance(c, A)
I don't know which copied which.
Why not use 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With