instance and class-hierarchy ?

B

Bror Johansson

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_superclasses_to(obj.__class__):
...

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

/BJ
 
R

Rene Pijlman

Bror Johansson:
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?

isinstance(obj,C)
 
I

I V

Bror said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top