【发布时间】:2012-06-16 21:53:30
【问题描述】:
这个递归函数(search_Bases)有望遍历每个基类和__init__。如何在不实际使用self 的情况下引用每个班级的self?我已经尝试了几件事,但我无法弄清楚。当我将 Child() 类更改为做类似的事情时,它可以工作。所以我不知道下一步该做什么。
def search_Bases(child=0):
if child.__bases__:
for parent in child.__bases__:
parent.__init__(self) # <-----I can't figure out how to initiate the class
# without referring to 'self'....
search_Bases(parent)
class Female_Grandparent:
def __init__(self):
self.grandma_name = 'Grandma'
class Male_Grandparent:
def __init__(self):
self.grandpa_name = 'Grandpa'
class Female_Parent(Female_Grandparent, Male_Grandparent):
def __init__(self):
Female_Grandparent.__init__(self)
Male_Grandparent.__init__(self)
self.female_parent_name = 'Mother'
class Male_Parent(Female_Grandparent, Male_Grandparent):
def __init__(self):
Female_Grandparent.__init__(self)
Male_Grandparent.__init__(self)
self.male_parent_name = 'Father'
class Child(Female_Parent, Male_Parent):
def __init__(self):
Female_Parent.__init__(self)
Male_Parent.__init__(self)
#search_Bases(Child)
child = Child()
print child.grandma_name
【问题讨论】:
-
这里是一个编辑过的子类的例子: class Child(Female_Parent, Male_Parent): def __init__(self): parents = [Female_Parent,Male_Parent] for parent in parents: parent.__init__(self)它似乎工作得很好。我看不出它有什么不同。
-
您的问题不清楚。你得到什么错误,或者你期望它没有做什么?另外请从您的代码中删除所有无关的空行,它们会使代码过长。
-
第二个想法...我想我知道...我从未真正实例化过该类,我只是通过 Class.__bases__ 引用它.....
-
欢迎使用 stackoverflow。你能解释一下你想用你的 search_Base 函数实现什么吗?您已经在调用子对象上的所有 inits。在 python 中,你很少需要调用
__init__(除了在另一个__init__方法中)。 -
对不起。我在网上只剩下几分钟就扔了这个。我没有正确编辑它或完全描述我所追求的。即使我想要没有它的代码,我也将 init def 留在了每个类中,这对我的情况没有帮助。但我找到了处理它的方法。基本上,我想在每个类定义中不显式地初始化每个父级。但是,无论如何,明确地这样做会更好(也许是唯一的方法)。对不起,令人困惑的帖子。以后我会使用更好的代码礼仪。 :P
标签: python class oop inheritance composition