0

この再帰関数(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
4

1 に答える 1

4

クラスの継承を正しく理解していないと思います。Pythonでは、

class Female_Parent(Female_Grandparent, Male_Grandparent):
    def __init__(self):

Female_ParentIS-Aを意味しますがMale_Grandparent、これはありそうもないようです。あなたが言うつもりだったのは

class Female_Parent(object):
    def __init__(self, female_grandparent, male_grandparent):

これには、誰が質問しているかによって役割が変わるという問題もあります。定義上、Male_Grandparent(彼の孫の)はMale_Parent(彼の子供たちの)またChild(彼の両親の)でもあります。

すべてのクラスを次のようにまとめることができます

class Person(object):
    def __init__(self, mother, father):

そこからさらに関係を導き出します。これにより、視点の矛盾がなく、はるかに単純な構造が得られますが、特定の人のリンクは「上」になるだけなので、それでもさらなる関係を評価する際に問題が発生します。特定の人は両親が誰であるかを知っていますが、彼らを特定することはできません。子供。

すべての人のリストを保持し、毎回リストを検索することはできますが(母親が幼稚園を回って「あなたは私の子供ですか?あなたですか?あなたは私の子供ですか?」と言っているように)、これは非常に非効率的です。

代わりに、各関係を双方向にすることができます。各親にはすべての子のリストがあり、各子にはすべての親のリストがあります。人の追加と削除は少し難しくなりますが、それだけの価値はあります。

以下は私が好きなものより長いですが、私がそれを作ることができる限り短いです。それはあなたのニーズにはるかによく合うはずです!

class Person(object):
    def __init__(self, name, sex, parents=None, children=None):
        """
        Create a Person
        """
        self.name = name
        self.sex = sex    # 'M' or 'F'

        self.parents = set()
        if parents is not None:
            for p in parents:
                self.add_parent(p)

        self.children = set()
        if children is not None:
            for c in children:
                self.add_child(c)

    def add_parent(self, p):
        self.parents.add(p)
        p.children.add(self)

    def add_child(self, c):
        self.children.add(c)
        c.parents.add(self)

    def __str__(self):
        return self.name

    def __repr__(self):
        return "Person('{}', '{}')".format(self.name, self.sex)

    #
    # Immediate relationships
    #
    # Each fn returns a set of people who fulfill the stated relationship
    #

    def _parent(self):
        return self.parents

    def _sibling(self):
        return set().union(*(p.children for p in self.parents)) - set([self])

    def _child(self):
        return self.children

    def _female(self):
        if self.sex=='F':
            return set([self])
        else:
            return set()

    def _male(self):
        if self.sex=='M':
            return set([self])
        else:
            return set()

    def relation(self, *rels):
        """
        Find the set of all people who fulfill the stated relationship

        Ex:
            self.relation("parent", "siblings")     # returns all aunts and uncles of self
        """
        # start with the current person
        ps = set([self])

        for rel in rels:
            # each argument is either a function or a string
            if callable(rel):
                # run the function against all people in the current set
                #   and collect the results to a new set
                ps = set().union(*(rel(p) for p in ps))
            else:
                # recurse to evaluate the string
                do = Person._relations[rel]
                ps = set().union(*(p.relation(*do) for p in ps))

        return ps

    def print_relation(self, *rels):
        print ', '.join(str(p) for p in self.relation(*rels))

#
# Extended relationships
#
# Supplies the necessary information for Person.relation() to do its job -
# Each key refers to a recursive function tree (nodes are string values, leaves are functions)
#
# (Unfortunately this table cannot be created until the Person class is finalized)
#
Person._relations = {
    "parent":        (Person._parent,),
    "mother":        (Person._parent, Person._female),
    "father":        (Person._parent, Person._male),
    "sibling":       (Person._sibling,),
    "sister":        (Person._sibling, Person._female),
    "brother":       (Person._sibling, Person._male),
    "child":         (Person._child,),
    "daughter":      (Person._child, Person._female),
    "son":           (Person._child, Person._male),
    "grandparent":   ("parent", "parent"),
    "grandmother":   ("parent", "mother"),
    "grandfather":   ("parent", "father"),
    "aunt":          ("parent", "sister"),
    "uncle":         ("parent", "brother"),
    "cousin":        ("parent", "sibling", "child"),
    "niece":         ("sibling", "daughter"),
    "nephew":        ("sibling", "son"),
    "grandchild":    ("child", "child"),
    "grandson":      ("child", "son"),
    "granddaughter": ("child", "daughter")
}

そして今、実際に:

mm  = Person('Grandma', 'F')
mf  = Person('Grandpa', 'M')
m   = Person('Mom', 'F', [mm, mf])
fm  = Person('Nana', 'F')
ff  = Person('Papi', 'M')
f   = Person('Dad', 'M', [fm, ff])
me  = Person('Me', 'M', [m, f])
s   = Person('Sis', 'F', [m, f])
joe = Person('Brother-in-law', 'M')
s1  = Person('Andy', 'M', [s, joe])
s2  = Person('Betty', 'F', [s, joe])
s3  = Person('Carl', 'M', [s, joe])

me.print_relation("grandmother")    # returns 'Nana, Grandma'
me.print_relation("nephew")         # returns 'Andy, Carl'
于 2012-06-17T01:59:31.700 に答える