I quickly browsed through section 9 of the Tutorial, tried some simple
Google searches: I'm not readily seeing how to test class type. Given some
object (might be an instance of a user-created class, might be None, might
be list, might be some other "standard" type object instance), how do you
test its type?
Python 2.2.2 (#1, Mar 17 2003, 15:17:58)
[GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.[color=blue][color=green][color=darkred]
>>> class A:[/color][/color][/color]
.... pass
....[color=blue][color=green][color=darkred]
>>> obj = A()
>>> obj[/color][/color][/color]
<__main__.A instance at 0x81778d4>
# Here, it's fairly obvious its an A-type object. A as defined in module
'__main__'.
# Some of the comparisons against "Python primitives", work as you might
expect...[color=blue][color=green][color=darkred]
>>> int[/color][/color][/color]
<type 'int'>[color=blue][color=green][color=darkred]
>>> type(3) == int[/color][/color][/color]
1[color=blue][color=green][color=darkred]
>>> ls = range(3)
>>> ls[/color][/color][/color]
[0, 1, 2][color=blue][color=green][color=darkred]
>>> type(ls)[/color][/color][/color]
<type 'list'>[color=blue][color=green][color=darkred]
>>> type(ls) == list[/color][/color][/color]
1[color=blue][color=green][color=darkred]
>>> type({}) == dict[/color][/color][/color]
1[color=blue][color=green][color=darkred]
>>> type(3.14) == float[/color][/color][/color]
1
# but this doesn't seem to extend to user-defined classes.[color=blue][color=green][color=darkred]
>>> dir(obj)[/color][/color][/color]
['__doc__', '__module__'][color=blue][color=green][color=darkred]
>>> obj.__module__[/color][/color][/color]
'__main__'[color=blue][color=green][color=darkred]
>>> type(obj)[/color][/color][/color]
<type 'instance'>[color=blue][color=green][color=darkred]
>>> type(obj) == A[/color][/color][/color]
0[color=blue][color=green][color=darkred]
>>> type(obj) is A[/color][/color][/color]
0
# The following "works", but I don't want to keep a set of instances to
compare against[color=blue][color=green][color=darkred]
>>> obj2 = A()
>>> type(obj) == type(obj2)[/color][/color][/color]
1
Comment