4

suppose you have:

class F:
    pass

then you make an instance:

g=F()

how can i check if the instance g is derived from the main class F?

Paul R
  • 208,748
  • 37
  • 389
  • 560
ame_math
  • 67
  • 1
  • 1
    The "main class" F? As opposed to what? Do you have another F class somewhere? Are you trying to exclude instances of subclasses? The way you've worded your question, it kind of sounds like you already know what class your object is an instance of. Your question is confusing. – user2357112 Mar 16 '16 at 17:43
  • Note that while you certainly can check the type of an object (or class of an instance), unless it's for debugging purposes, it's usually not a good idea as it's very non-object-oriented and makes your code more "brittle" (easily broken) when you change or try to enhance it in the future. – martineau Mar 16 '16 at 17:56
  • thanks all for the help – ame_math Mar 17 '16 at 02:10

1 Answers1

8

You can do this:

if isinstance(obj, MyClass):
     print "obj is my object"

So for your example:

if isinstance(g, F):
    print "obj is my object"

Use this at your peril, sometimes it's Easier to Ask Forgiveness than Permission.

Community
  • 1
  • 1
ml-moron
  • 888
  • 1
  • 11
  • 22