Chris
Chris

Reputation: 10041

rationale behind python class/subclass inheritance

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

Upvotes: 3

Views: 177

Answers (1)

Fred Foo
Fred Foo

Reputation: 363467

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)

Upvotes: 4

Related Questions