I get an error message:
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)
I am sure this is a well-known paradigm, since it seems to be a fairly common problem of using a hierarchical class (self-promotion class). I know that I can change its_parent_org_unit type as an object , and it works, but it seems to be wrong, primarily because it renounces my ability to check types in my calls. If its_parent_org_unit changed as an object type, I get the correct results:
IBM_Worldwide IBM_Worldwide->IBM_USA IBM_Worldwide->IBM_Asia IBM_Worldwide->IBM_Asia->IBM_China
I am open to thought and suggestions. What is the most "pythonic" way to do such things?
PS: What is the name of this kind of paradigm / self-defining class "self referencing class" that I could use to search for other suggestions?
python class type-hinting
Rg abbott
source share