【问题标题】:Inheritance in python 2.7python 2.7中的继承
【发布时间】:2014-01-14 15:38:25
【问题描述】:

我正在尝试构建一个框架来解析非常具体的文本结构。 我正在处理的结构很丰富,并且有一个已知的模式,类似于 xml。 我正在尝试构建一个框架来进行解析。文本有不同的部分,我预计将来会添加更多的部分代码。为了补偿,我正在尝试构建一系列可以根据需要换入或换出的派生类。

我以为一切都按计划进行,直到我开始编写第一个派生类。 基类在__init__ 内部有一些功能,我希望我能在所有具体派生类中免费获得这些功能。然而,情况似乎根本不是这样。

这是一个简单的例子来说明我的问题: 我希望输出是:

['memberA', 'memberB', 'memberC'], ['DerivedA', 'DerivedB', 'DerivedC']

class base(object):
    def __init__(self):
        members = [attr for attr in dir(self) if not callable(attr) and not attr.startswith("__")]
        print members

class test(base):
    def __init__(self):
        self.memberA = None
        self.memberB = None
        self.memberC = None


class test2(test):
    def __init__(self):
        self.DerivedA = None
        self.DerivedB = None
        self.DerivedC = None

t = test()
t2 = test2()

有人可以向我解释一下,为什么打印功能没有按我的预期工作吗?

编辑: 根据下面的答案:我现在有这个问题:

如果 base.__init(self) 看起来像这样会怎样:

class base(object):
    def __init__(self, text):

我是否必须将派生类定义为:

class test(base):
    def __init__(self, text):
        base.__init__(self, text)

我希望至少可以免费获得参数对象引用

【问题讨论】:

    标签: python oop inheritance python-2.7


    【解决方案1】:

    在 Python 中,您必须在 test.__init__ 内显式调用基类的 __init__

    class test(base):
        def __init__(self):
            base.__init__(self)
    

    或者,如果您希望支持多重继承,请使用super

    class test(base):
        def __init__(self):
            super(test, self).__init__()
    

    如果base.__init__ 看起来像

    class base(object):
        def __init__(self, text):
    

    那么test.__init__ 确实应该看起来像

    class test(base):
        def __init__(self, text):
            base.__init__(self, text)
    

    请参阅 Guido van Rossum 的博客why self is explicit in Python


    附言。 PEP8 建议使用 CapWords 作为类名。

    【讨论】:

      【解决方案2】:

      你正在覆盖 test2 中的 init

      以下代码将在测试中完成覆盖 init。所以 init 函数中不再有 print int。

      def __init__(self):
          self.DerivedA = None
          self.DerivedB = None
          self.DerivedC = None
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-01
        • 1970-01-01
        • 2016-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多