如何在Python中创建有界的int?

时间:2019-06-19 23:13:40

标签: python integer limit boundary bounded-types

我想创建一个从$rawId = (isset($_GET["id"]) ? $_GET["id"] : null); $rawStatus = (isset($_GET["status"]) ? $_GET["status"] : null); if (!is_int($rawId)) { //handle } if (!is_bool($rawStatus)) { //handle } 继承而来的类,但是在可以设置的数字上设置下限和上限。

例如,如果下限为int,则2应该引发异常。

我正在苦苦挣扎,因为a = MyClass(1)似乎没有int函数,因此我不确定如何从中继承,我的尝试给我带来了错误。

我应该怎么做?

2 个答案:

答案 0 :(得分:0)

这是即时的,不会处理很多错误。

class boundedInt:

    def __init__(self, lower, upper):
        self.x = None
        if (lower <= upper):
            self.lower = lower
            self.upper = upper
        else:
            raise ValueError("Lower Bound must be lesser than Upper Bound".format())  

    def assign(self, x):
        if (x>= self.lower and x<=self.upper):
            self.x = x
            return self.x
        else:
            raise ValueError("Not in bounds")

myInt = boundedInt(15,20) # create object myInt
f = myInt.assign(17) # assigns value to a variable

答案 1 :(得分:-1)

尝试一下。它应该同时适用于(Pdb) rnn_output tensor([[[ 0.2663, 0.3429, -0.0415, ..., 0.1275, 0.0719, 0.1011], [-0.1272, 0.3096, -0.0403, ..., 0.0589, -0.0556, -0.3039], [ 0.1064, 0.2810, -0.1858, ..., 0.3308, 0.1150, -0.3348], ..., [-0.0929, 0.2826, -0.0554, ..., 0.0176, -0.1552, -0.0427], [-0.0849, 0.3395, -0.0477, ..., 0.0172, -0.1429, 0.0153], [-0.0212, 0.1257, -0.2670, ..., -0.0432, 0.2122, -0.1797]]], grad_fn=<StackBackward>) (Pdb) hidden tensor([[[ 0.1700, 0.2388, -0.4159, ..., -0.1949, 0.0692, -0.0630], [ 0.1304, 0.0426, -0.2874, ..., 0.0882, 0.1394, -0.1899], [-0.0071, 0.1512, -0.1558, ..., -0.1578, 0.1990, -0.2468], ..., [ 0.0856, 0.0962, -0.0985, ..., 0.0081, 0.0906, -0.1234], [ 0.1773, 0.2808, -0.0300, ..., -0.0415, -0.0650, -0.0010], [ 0.2207, 0.3573, -0.2493, ..., -0.2371, 0.1349, -0.2982]], [[ 0.2663, 0.3429, -0.0415, ..., 0.1275, 0.0719, 0.1011], [-0.1272, 0.3096, -0.0403, ..., 0.0589, -0.0556, -0.3039], [ 0.1064, 0.2810, -0.1858, ..., 0.3308, 0.1150, -0.3348], ..., [-0.0929, 0.2826, -0.0554, ..., 0.0176, -0.1552, -0.0427], [-0.0849, 0.3395, -0.0477, ..., 0.0172, -0.1429, 0.0153], [-0.0212, 0.1257, -0.2670, ..., -0.0432, 0.2122, -0.1797]]], grad_fn=<StackBackward>) int

float

def BoundedNumber(number_class): def BoundedNumberClassCreator(class_name, lower_bound, upper_bound): if upper_bound and lower_bound and upper_bound < lower_bound: raise ValueError(f"Upper bound {upper_bound} is lower than the lower bound {lower_bound}") def new(cls, number): if lower_bound and number < lower_bound: raise ValueError(f"{number} is below the lower bound of {lower_bound} for this class") if upper_bound and upper_bound < number: raise ValueError(f"{number} is above the upper bound of {upper_bound} for this class") return number_class(number) return type(class_name, (number_class,), {"__new__": new, "__doc__": f"Class that acts like `{number_class.__name__}` but has an inclusive lower bound of {lower_bound} and an inclusive upper bound of {upper_bound}", "lower_bound": lower_bound, "upper_bound": upper_bound}) return BoundedNumberClassCreator BoundedInt = BoundedNumber(int) BoundedFloat = BoundedNumber(float) if __name__ == "__main__": IntBetween50And150 = BoundedInt('IntBetween50And150', 50, 150) print(IntBetween50And150(100) == 100) # True try: IntBetween50And150(200) except ValueError as e: print(f"Caught the ValueError: {e}") # Caught the value error: 200 is above the upper bound of 150 for this class print(IntBetween50And150(50.5)) # 50 print(IntBetween50And150.__doc__) # Class that acts like `int` but has an inclusive lower bound of 50 and an inclusive upper bound of 150 继承子类的困难之处在于它没有int函数。相反,您必须使用__init__函数。

__new__类负责处理此问题,它定义了一个BoundedNumber函数,该函数都通过调用{{来运行__new__(或intfloat函数1}}(或__new__),但在执行此操作之前也要对边界进行自己的检查。

由于我们要动态创建一个新类,因此我们将不得不使用int函数。这样一来,我们便可以在运行时创建具有所需边界的新类。

从技术上讲,要回答您的问题,您只需要在使用float的任何地方插入type的{​​{1}},但由于它适用于BoundedNumberClassCreator s好吧,我想将其封装起来以减少重复的代码。

如果您int然后创建number_class,即使float在指定的范围内,它也会引发错误,因此此解决方案很奇怪。如果您不喜欢此功能,则可以在ZeroToOne = BoundedInt('ZeroToOne', 0, 1)的{​​{1}}方法内部交换支票的顺序和返回。