我得到错误:
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
将be 的类型更改为object
有效,但是这样做似乎是错误的事情,主要是因为它削弱了我检查呼叫类型的能力。将其its_parent_org_unit
更改为类型后,object
我得到正确的结果:
IBM_Worldwide
IBM_Worldwide->IBM_USA
IBM_Worldwide->IBM_Asia
IBM_Worldwide->IBM_Asia->IBM_China
我愿意考虑和提出建议。做这种事情的最“ pythonic”方法是什么?
PS:这种“自我引用类”范例/问题的名称是什么,我可以用它来查找其他建议吗?
您的问题是您想使用类型提示,但您希望此类本身能够接受自己类型的参数。
类型提示PEP(0484)解释说,您可以使用类型名称的字符串版本作为前向引用。这个例子的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
。这将自动将注释存储为字符串,而不是对其进行评估,因此您可以执行
from __future__ import annotations
class OrgUnit(object):
def __init__(self,
an_org_name: str,
its_parent_org_unit: OrgUnit= None
):
...
按计划,它将成为Python 4.0中的默认设置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句