Skip to content
Dmytro Piliugin edited this page Sep 16, 2017 · 16 revisions

Inspecting the Class Type

Some koans may ask you for the __class__ attribute of an object:

AssertionError: '-=> FILL ME IN! <=-' != <type 'str'>

What does __class__ attribute do? It tells you what the class type is for a given object (on the left hand side of the period). Let's look at that for a string object:

To the Python Console (IDLE) robin! And run this: "batman".__class__

"batman".class

Notice it returns this: <type 'str'>

Which is the same thing we're seeing from the koans runner:

AssertionError: '-=> FILL ME IN! <=-' != <type 'str'>

So "batman".__class__ == <type 'str'> then right?

Not exactly...

"batman" == <type 'str'>

"batman".__class__ is DISPLAYED as <type 'str'>, but the value is actually the class name. Which is just str. NO QUOTES!

"batman" == str

Class Types With Namespaces

Note: These examples show Python 2 output. Python 3 output will look a little different.

Some classes are more confusing to inspect using __class__. For example:- Exception classes.

To demonstrate we need to capture an exception object from the python console:

catching an exception

We now have the exception object stashed away in the ex2 variable. So which part of that is the class type name? We can inspect it with the __class__ attribute:

ex2.class

So... that would mean that the ex2.__class__ is equal to exceptions.NameError, right?

Uh, not exactly:

ex2.class != exceptions.NameError

The thing is, when used in comparison __class__ isn't interested in which module a class lives in. It just looks at the actual class name. You get a more honest view of what the __class__ value really by chaining it to __name__ forcing it to display a briefer version:

ex2.class == NameError

Note: That result is surrounded by quotes. so __class__ is not actually equal to __class__.__name__.

So when asked for a __class__ value by Python Koans, always give the straight class name or type. No periods period. Got it?

Clone this wiki locally