2013-03-25 46 views
3

当我创建一个父类和子类,如下所示,为什么父类的参数不会自动被子类拉入?Python类/子类继承的基本原理

我明白,明确的比较好,但我在什么情况下该代码知道...

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 2013-03-25 15:04:41

+0

两者都可以工作,这取决于你正在尝试做什么。没有足够的信息来找出你的问题在哪里。 – cmd 2013-03-25 15:06:28

+0

我编写的孩子分类很少(需要自己的__init__)接受与超类相同的参数,并在未修改的情况下传递它们。大多数人接受更少的参数或不同的参数(并以某种方式计算参数传递给超类)。 – delnan 2013-03-25 15:06:33

回答

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)