Python类/子类继承背后的原理

3
当我创建如下的父类和子类时,为什么子类不会自动继承父类的参数?
我明白显式更好,但我想知道在什么情况下这段代码...
class testParent(object):
    def __init__(self,testParentParam1,testParentParam2):
        pass


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

比这段代码更好...

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


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

2
无论如何,当构造函数为空时很难判断哪个更好。 - bereal
两种方法都可以,这取决于你想要做什么。这里没有足够的信息来确定你的问题所在。 - cmd
我编写的一些子类(需要自己的__init__)接受了与超类相同的参数并将它们未经修改地传递下去。大多数子类接受较少的参数或不同的参数(并以某种方式计算要传递给超类的参数)。 - user395760
1个回答

4

派生类扩展基类。这意味着在构造时,它们可能需要更多/更少/不同的信息来进行扩展。考虑以下情况:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接