LZOO
LZOO

Reputation: 125

How to distinguish between an instance of a class and normal datatype int/bool/float/etc

In python I am trying to integrate through an object wo (user defined) and wo.obj is another user defined object how do I tell it is an instance of a class rather than normal data types?

type(wo.obj)
<class '__main__.test'>

type(wo.obj) is types.InstanceType
False

type(wo.obj) is types.ClassType
False

Upvotes: 0

Views: 110

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375535

To check whether an instance is in a specific class you can use isinstance:

mc = MyClass()
isinstance(mc, MyClass) # True

.

Note: it is True for subclasses, and there are some other quirks, see this answer to a similar question.

If you just check type you will see the result is <type 'instance'> no matter which "user-defined" class it is an instance of.

type(notmc).__name__ == 'instance' #True

I suspect this should come with some form of health warning, as checking whether the class is of instance type seems not a very intensive check.

Upvotes: 3

Related Questions