Python: How to use isinstance from parent to determine if it is a specific child

1.4k views Asked by At

I have a few classes

class Parent():
    def DoThing():
        if isinstance(self, 'child1'):
            DoSomething()
        elif:
            DoSomethingElse()

import Parent
class Child1(Parent):
    def DoThing():
        #Do some things here
        super.DoThing()

import Parent
class Child2(Parent)
    def DoThing():
        #Do other things
        super.DoThing()

The problem I am having is that I want to check whether the instance of the class is the parent itself or one of the children.

The point of failure is when interpreting the Parent, the process fails as the interpreter doesn't know what Child1 is. I cannot import Child1 as that would cause recursion.

I have created a work around to this by defining a method in the parent and child1.

def IsChild1Instance(self):
    return True/False

Is there a better and cleaner way of doing this?

1

There are 1 answers

0
Martijn Pieters On BEST ANSWER

Your parent class should not care about sub-classes. Use different implementations of a method instead:

class Parent:
    def do_thing(self):
        self.do_something_delegated()

    def do_something_delegated(self):
        pass

class Child1(Parent):
    def do_something_delegated(self):
        # do child1 specific things

class Child2(Parent)
    def do_something_delegated(self):
        # do child2 specific things