为正在定义的类型的对象键入Hinting

时间:2016-02-25 03:22:24

标签: python class type-hinting

我收到错误:

NameError: name 'OrgUnit' is not defined
class OrgUnit(object):

    def __init__(self,
                 an_org_name: str,
                 its_parent_org_unit: OrgUnit= None
                 ):
        self.org_unit_name = an_org_name
        self.parent_org_unit = its_parent_org_unit

    def __str__(self):
        if self.parent_org_unit:
            parent_org_unit_name = self.parent_org_unit.__str__()
            return parent_org_unit_name + "->" + self.org_unit_name
        else:
            return self.org_unit_name


if __name__ == '__main__':
    ibm_worldwide = OrgUnit("IBM_Worldwide")
    ibm_usa = OrgUnit("IBM_USA", ibm_worldwide)
    ibm_asia = OrgUnit("IBM_Asia", ibm_worldwide)
    ibm_china = OrgUnit("IBM_China", ibm_asia)
    print(ibm_worldwide)
    print(ibm_usa)
    print(ibm_asia)
    print(ibm_china)

我确信这是一个已知的范例,因为它似乎是一个非常常见的分层类使用问题(自引用类)。我知道我可以将its_parent_org_unit的类型更改为object并且它可以正常工作,但这似乎是错误的做法,主要是因为它能够检查我在调用中检查类型的能力。将its_parent_org_unit更改为object类型后,我得到了正确的结果:

IBM_Worldwide
IBM_Worldwide->IBM_USA
IBM_Worldwide->IBM_Asia
IBM_Worldwide->IBM_Asia->IBM_China

我愿意接受各种想法和建议。做这种事的最“pythonic”方式是什么?

PS:这种“自引用类”范例/问题的名称是什么,我可以用来查找其他建议?

1 个答案:

答案 0 :(得分:19)

您的问题是您希望使用类型提示,但您希望此类本身能够获取其自己类型的参数。

类型提示PEP(0484)解释说您可以使用string version of the type's name as a forward reference。这个例子有一个Tree数据结构,听起来与这个OrgUnit非常相似。

例如,这有效:

class OrgUnit(object):

    def __init__(self,
                 an_org_name: str,
                 its_parent_org_unit: 'OrgUnit' = None
                 ):

在Python 3.7中,您可以使用from __future__ import annotations激活postponed evaluation of annotations。这将自动将注释存储为字符串而不是评估它们,因此您可以执行

from __future__ import annotations

class OrgUnit(object):
    def __init__(self,
                 an_org_name: str,
                 its_parent_org_unit: OrgUnit= None
                 ):
        ...

这计划成为Python 4.0的默认设置。