0

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
3
  • 2
    Python primitives are also instances of classes. Everything's an object. Commented Sep 7, 2012 at 14:46
  • 1
    There is no such thing as a normal datatype as opposed to instances of classes. There are a couple of "builtin" types, but they are objects in pretty much every sense of the word and distinguishing them almost never makes sense. Whatever problem you are trying to solve, this is an entirely wrong approach. Delete this question and ask a question about your actual problem. (cf. the XY Problem) Commented Sep 7, 2012 at 14:48
  • Again, why do you need to know? There's probably a better way to do what you want than to check the type, but we can't say until you tell us more about your problem. Commented Sep 7, 2012 at 15:16

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What if I want something more generic as in I want to know if it is an instance of any class. I have defined many different classes. Checking for each one of them can be a handful.
As all datatypes are objects of some sort its best just to check if it is an int/float/str/etc and eliminate them. Thank you for your answer:>
@LZOO made it less cheeky, hope it helped.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.