我想创建一个自定义数据类型,它的行为基本上类似于普通 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

任何提示表示赞赏。谢谢!

最佳答案

使用 __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

关于python - 扩展 Python 的 int 类型以仅接受给定范围内的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2635148/

10-12 21:03