Skip to main content
 首页 » 编程设计

python之python 2.7 中的继承

2025年05月04日15飞鱼

我正在尝试构建一个框架来解析非常具体的文本结构。 我正在处理的结构很丰富并且有一个已知的模式,类似于 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 中,必须在 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 作为类名。