扩展Python的int类型以仅接受给定范围内的值

igo*_*gor 4 python types

我想创建一个自定义数据类型,它基本上像普通的一样int,但值限制在给定范围内.我想我需要某种工厂功能,但我无法弄清楚如何做到这一点.

myType = MyCustomInt(minimum=7, maximum=49, default=10)
i = myType(16)    # OK
i = myType(52)    # raises ValueError
i = myType()      # i == 10

positiveInt = MyCustomInt(minimum=1)     # no maximum restriction
negativeInt = MyCustomInt(maximum=-1)    # no minimum restriction
nonsensicalInt = MyCustomInt()           # well, the same as an ordinary int
Run Code Online (Sandbox Code Playgroud)

任何提示都表示赞赏.谢谢!

bob*_*nce 5

使用__new__覆盖不变类型的建设:

def makeLimitedInt(minimum, maximum, default):
    class LimitedInt(int):
        def __new__(cls, x= default, *args, **kwargs):
            instance= int.__new__(cls, x, *args, **kwargs)
            if not minimum<=instance<=maximum:
                raise ValueError('Value outside LimitedInt range')
            return instance
    return LimitedInt
Run Code Online (Sandbox Code Playgroud)