Python引用构造到它自己

时间:2017-05-05 07:13:18

标签: python python-3.x oop

我想添加一个引用表,但这似乎不可能。 你看到一种方法来避免这种情况吗?还是其他任何建议? 我想定义一个家庭成员之间的关系。

class Person():
    """
    Person and possibly something we could use as an user.
    """

    RELATIONSHIPS = dict(
        CHILD={
            'opposite': Person.RELATIONSHIPS.PARENT
        },
        PARENT={
            'opposite': Person.RELATIONSHIPS.CHILD
        }
    )

1 个答案:

答案 0 :(得分:1)

也许是这样的?

class Person():    
    RELATIONSHIPS = dict(CHILD={}, PARENT={})
    RELATIONSHIPS['CHILD']['opposite'] = RELATIONSHIPS['PARENT']
    RELATIONSHIPS['PARENT']['opposite'] = RELATIONSHIPS['CHILD']

请注意,您无法将其视为Person.RELATIONSHIPS.CHILD.opposite,而是Person.RELATIONSHIPS['CHILD']['opposite']等。

或者您可以使用临时变量:

class Person():
    _parent = {}
    _child = {'opposite': _parent}
    _parent['opposite'] = _child
    RELATIONSHIPS = dict(CHILD=_child, PARENT=_parent)
    del _parent, _child