Jump to content

Testing if a class inherits another class

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
matio

matio

    Learning Programmer

  • Members
  • PipPipPip
  • 51 posts
Hi everyone, as the title suggests I want to know if a class inherits another class. I know that I can use isinstance but the class I want to use takes a long time to load.

class Base:

    pass


class InheritsBase(Base):

    def __init__(self):

        do_lots_of_stuff_that_takes_a_while()


isinstance(InheritsBase(), Base) # too slow!

# i need to do something like this:

doesinherit(InheritsBase, Base)



Help is appreciated!

#2
Excited

Excited

    Newbie

  • Members
  • PipPip
  • 27 posts
Use issubclass, or you could add a 'check' variable to the base class and see if you can access it.

This is a method to check if one class inherits another but I'm guessing it's very slow:

class Base(object):
    def __init__(self):
        self.check = 'Base' #or another unique value

class InheritsBase(Base):
    def __init__(self):
        Base.__init__(self)

def inherits(base, inheritor):
    a = base().check
    b = inheritor().check
    try:
            if b == a:
                return True
            else:
                return False
    except AttributeError:
            return False

print inherits(Base, InheritsBase)
You could potentially speed it up by doing something like this to make it skip all the other stuff in InheritsBase when just checking:

class Base(object):
    def __init__(self):
        self.check = 'Base' # or another unique value (for multiple checks)

class InheritsBase(Base):
    def __init__(self, checking=False):
        Base.__init__(self)
        if checking: return # any code after this does not get executed
        print 'que2' # does not get executed when checking

def inherits(base, inheritor):
    a = base().check
    b = inheritor(checking=True).check
    try:
            if b == a:
                return True
            else:
                return False
    except AttributeError:
            return False

print inherits(Base, InheritsBase)
This does not work on the Base class as it needs to be initiated to be properly inherited, which happens here:
Base.__init__(self)

Edited by Excited, 12 August 2010 - 03:48 AM.
mistake