gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:23:41 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com