instance and class-hierarchy ?

I V wrongbad at gmail.com
Wed Mar 29 21:25:38 CEST 2006


Bror Johansson wrote:
> Is there a good and general way to test an instance-object obj for having a
> class belonging to a certain "sub-tree" of the hierarchy with a common
> parent class C?

If I understand you correctly, isinstance ought to do the job:

class A(object):
    pass

class B(A):
    pass

class C(B):
    pass

c = C()

assert isinstance(c, C)
assert isinstance(c, B)
assert isinstance(c, A)

However, I'm not sure it's great style to have to inquire about the
type of an object, as I would worry it would be fragile if you redesign
your class hierarchy. Maybe an alternative would be to add a method to
your 'C' class to accomplish whatever it is you need to do? Still, if
that doesn't work (sometimes algorithms just are tightly coupled to the
specific class hierarchy, and you can't avoid it), isinstance should
work.




More information about the Python-list mailing list