5
class A:
   pass

class B(A):
   pass

How can I check that var is instance of B, not A, without referencing A. I have around 50 classes that subclass some class. I want to check whether instance is a child. Something like not isinstance(var, A).

Is there any way?

Paul R
  • 2,631
  • 3
  • 38
  • 72

5 Answers5

6

isinstance(object, classinfo) checks if the object is an instance of (or subclass of) the class given as second parameter.

type(object) returns the exact type of the object.

So you can check whether the object is an instance of a subclass of A, but not A itself, you can do something like the following.

if isinstance(obj, A) and not type(obj) == A:
    print("is subclass of A")
else:
    print("is either A or completely unrelated")

For reference:

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
0

So I assume that B does something particular that A can't do. Ie it has a method that A doesn't. So one way to check that the instance is from B is to use the following.

if hasattr(my_instance, 'method_name_particular_to_b'):
    # do this

This will check if that method exists on my_instance if it does. You can treat it as an instance from B, otherwise treat it as an instance from A.

Jonathan
  • 8,453
  • 9
  • 51
  • 74
0

It is really hard to use isinstance and judge whether a particular variable var is an instance of a subclass or superclass. What you can in fact do is specify a special property __class__ which can tell you about the instance's class.

for example:

class A:
    @property
    def __class__(self):
        return '__main__.A'

class B(A):
    @property
    def __class__(self):
        return '__main__.B'

b = B()
a = A()

print b.__class__
> '__main__.B'

print a.__class__
> '__main__.A'

If you however inherit class A with object you can check the behaviour without specifying these properties.

class A(object):
    pass

class B(A):
    pass

b = B()
a = A()

print b.__class__
> '__main__.B'

print a.__class__
> '__main__.A'

PS: I referred this SO question although it is in Java

Arpit Goyal
  • 2,212
  • 11
  • 31
0

Not elegant, but seems working: not var.__class__.__name__=='A'

Paul R
  • 2,631
  • 3
  • 38
  • 72
0

You can find the type of an instance using __class__.

var.__class__ will give you the specific type of the object.

salmanwahed
  • 9,450
  • 7
  • 32
  • 55