Class able to describe its heirarchy

Please see the following Python code:

class Object:
    @classmethod
    def __repr__(cls):
        typeNames = []
        try:
            for t in cls.mro():
                typeNames.append(t.typeName)
        except AttributeError:
            pass
        return " > ".join(reversed(typeNames))

class Vehicle(Object):
    typeName = "MyVehicle"
class FourWheeler(Vehicle):
    typeName = "MyFourWheeler"
class Car(FourWheeler):
    typeName = "MyCar"

print(Car())

outputs:

MyVehicle > MyFourWheeler > MyCar

I would like to know if something like this is possible in Haxe and if yes then how?

I am looking to represent some type heirarchies like this and find the mro() facility of Python very useful for this, but want it to be portable in other languages via Haxe.

1 Like

You can call Type.getSuperClass() in a loop until you reach the top of the hierarchy / null.

2 Likes

Not sure what you are exactly looking for (I don’t know much about python), but maybe this gives some direction.

This can be approached in multiple ways, a common pattern is to use OOP, which means you create classes and extend them.

class Vehicle { 
   public final names:Array<String> = [];
   public function new() {
     this.names.push("Vehicle");
  }

  public function toString() return names.join(" > ");
}
class Car extends Vehicle { 
   public function new() {
     super();
     this.names.push("Car");
   }
}
class MyVehicle extends Car { public function new() {
     super();
     this.names.push("MyVehicle");
   }
}
class FourWheeler extends Car {public function new() {
     super();
     this.names.push("FourWheeler");
   }
 }

Then you can do trace(new FourWheeler().toString()) which will log MyFourWheeler > MyCar > Vehicle

If it’s more about describing structures, you might want to look into enums:

typedef CarData = {
  name: String;
}

enum Car {
  MyVehicle(data:CarData);
  FourWheeler(data:CarData);
}

Thanks for your reply but this creates a separate array for each instance, which seems unnecessary. Would be good to have a more memory efficient solution.