By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,309 Members | 2,035 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,309 IT Pros & Developers. It's quick & easy.

instance and class-hierarchy ?

P: n/a
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

Mar 29 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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)

--
René Pijlman
Mar 29 '06 #2

P: n/a
I V
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.

Mar 29 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.