Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 265
Chris Avatar asked Sep 27 '26 21:09

Chris


1 Answers

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)
like image 73
Fred Foo Avatar answered Sep 30 '26 11:09

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!