3

When I create a parent class and child class as shown below, why don't the arguments from the parent class automatically get pulled in by the child class?

I understand that explicit is better, but I'm wondering in what circumstance this code...

class testParent(object):
    def __init__(self,testParentParam1,testParentParam2):
        pass


class testChild(testParent):
    def __init__(self,testParentParam1,testParentParam2,testChildParam1,testChildParam2):
        pass

Is better than this code...

class testParent(object):
    def __init__(self,testParentParam1,testParentParam2):
        pass


class testChild(testParent):
    def __init__(self,testChildParam1,testChildParam2):
        pass
3
  • 2
    It's hard to tell which is better while the constructors are empty anyway. Commented Mar 25, 2013 at 15:04
  • Both can work, it depends on what you are trying to do. There is not enough info here to figure out where your problem is. Commented Mar 25, 2013 at 15:06
  • Few of the child classed I've written (that needed a __init__ of its own) accepted the same arguments as the superclass and passed them on unmodified. The majority accepted fewer arguments or different arguments (and somehow computed the arguments to pass to the superclass). Commented Mar 25, 2013 at 15:06

1 Answer 1

4

Derived classes extend base classes. That means they might need more/less/different information at construction time to do their extending. Consider:

class BaseTextDocument(object):
    def __init__(self, content):
        self.content = content

class WordDocument(object):
    def __init__(self, path, word_version="guess_from_file"):
        content = parse_word_document(path, word_version)
        super(WordDocument, self).__init__(content)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.