gpt4 book ai didi

python - 正在定义的类型对象的类型提示

转载 作者:行者123 更新时间:2023-12-05 07:43:46 25 4
gpt4 key购买 nike

<分区>

我得到错误:

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:这种“自引用类”范例/问题的名称是什么,我可以用它来查找其他建议?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com