I want to create a class that subclasses from int, but sets a lower bound and upper bound on what number it can be be.
For example, if the lower bound is 2, then a = MyClass(1) should raise an exception.
I'm struggling because int doesn't seem to have an __init__ function, so I'm not sure how to subclass from it, and my attempts are giving me errors.
How should I go about doing this?
Try this. It should work both for
ints andfloats:The hard part with subclassing from
intis that it doesn't have an__init__function. Instead, you have to use the__new__function.The
BoundedNumberclass takes care of this, defining a__new__function that both runs theint(orfloat)__new__function by callingint(orfloat), but also runs its own checks on the bounds before doing so.Since we want to dynamically create a new class, we're going to have to use the
typefunction. This will allow us to create a new class with whatever bounds we want during runtime.Technically, to answer your question, you only need the
BoundedNumberClassCreatorwithintput in everywhere that thenumber_classis used, but since it works forfloats as well, I figured I'd encapsulate it to reduce duplicate code.One odd thing about this solution if if you
ZeroToOne = BoundedInt('ZeroToOne', 0, 1)and then createi = ZeroToOne(1.1)it will throw an error, even thoughint(1.1)is within the designated range. If you don't like this functionality, you can swap the order of the checks and the return inside of thenewmethod of theBoundedNumberClassCreator.