我正在尝试建立一个用于解析非常特定的文本结构的框架。我正在处理的结构很丰富,并且具有类似于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中,您必须在__init__
内部显式调用基类test.__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的博客,了解为什么self
在Python中是显式的。
PS。PEP8建议使用CapWords作为类名。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句