【问题标题】:rationale behind python class/subclass inheritancepython类/子类继承背后的基本原理
【发布时间】:2013-03-15 03:10:14
【问题描述】:

当我如下图创建父类和子类时,为什么父类的参数没有自动被子类拉进来?

我知道显式更好,但我想知道这段代码在什么情况下......

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

【问题讨论】:

  • 在构造函数为空的情况下,很难判断哪个更好。
  • 两者都可以,这取决于您要做什么。这里没有足够的信息来确定您的问题出在哪里。
  • 很少有我写过的子类(需要一个自己的__init__)接受与超类相同的参数并未经修改地传递它们。大多数人接受较少的参数或不同的参数(并以某种方式计算要传递给超类的参数)。

标签: python class inheritance subclass


【解决方案1】:

派生类扩展基类。这意味着他们可能在施工时需要更多/更少/不同的信息来进行扩展。考虑:

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)

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2010-10-23
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多