Below is a simplified version of the code I have:
class Base:
def __new__(klass, *args):
N = len(args)
try:
return [Sub0, Sub1, Sub2][N](*args)
except IndexError:
raise RuntimeError("Wrong number of arguments.") from None
class Sub0(Base): pass
class Sub1(Base): pass
class Sub2(Base): pass
This code does not work. My understanding for the reason it doesn't work is that my base class definition is dependent upon definition of the subclasses, which are in turn dependent on the base class.
What I am trying to accomplish is to create an API (for myself) in which I can do things like the following:
obj = Base(1,2)
assert type(obj) == Sub2
obj = Base()
assert type(obj) == Sub0
assert isinstance(obj, Base)
I might be asked why, exactly, I want to be able to write code like this. The answer is it seems like it will be useful for a project I'm working on. However, I am considering abandoning the subclasses and doing it this way instead:
obj = Base(1,2)
assert obj.type == "Sub2"
obj = Base()
assert obj.type == "Sub0"
assert isinstance(obj, Base)
As a relatively inexperienced programmer, I'm still trying to figure out what I should be doing for my particular problem.
However, the focus of this question is: if there are situations where using the base class and subclasses in this way makes sense, how can I make this work the way I have described? On the other hand, if it definitely does not ever - or at least, very rarely - make sense to try and do this (in Python, I mean - Python is different from other languages), why is this true?