instance and class-hierarchy ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bror Johansson

    #1

    instance and class-hierarchy ?

    Hi,

    I have a class-hierarchy (fairly deep and fairly wide).

    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?

    Testing for presence of attributes created at __init__ time is not
    considered general.

    Testing presence in the set of (manually enumerated) classes belonging to
    the "subtree" is not considered general.

    Testing like this:

    if C in [obj.__class__] + list_of_supercl asses_to(obj.__ class__):
    ...

    is general but I'm looking for a better way, if there is one.

    /BJ



  • Rene Pijlman

    #2
    Re: instance and class-hierarchy ?

    Bror Johansson:[color=blue]
    >I have a class-hierarchy (fairly deep and fairly wide).
    >
    >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?[/color]

    isinstance(obj, C)

    --
    René Pijlman

    Comment

    • I V

      #3
      Re: instance and class-hierarchy ?

      Bror Johansson wrote:[color=blue]
      > 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?[/color]

      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.

      Comment

      Working...