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

标签 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

感谢任何提示。谢谢!

最佳答案

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

相关文章:

python - Speedwise,Pharo 与 Python3 相比如何?

python - 如何使 Python 中的字符串解析不那么笨拙?

python - selenium.common.exceptions.ElementNotVisibleException : Message: element not visible while invoking send_keys in ubuntu headless browser through python

types - Go 中的别名类型仅在未命名时才可分配?

c# - 在给定 Collection<T> 对象的情况下查找 "T"

typescript - 在 TypeScript 中使用映射类型来限制方法类型

powershell - 使用 powershell 将整数存储在自定义对象中

python - (Pygame) 鼠标悬停检测的问题

ruby-on-rails - 在 Rails 和 PostgreSQL 中用于 Facebook 用户 ID 的数据类型

python - 使用 dictConfig 时将 Python 日志设置为覆盖日志文件?