如何创建一个扩展具有输入验证的`int`基类的类? [英] How to create a class that extends the `int` base class that has input validation?

查看:54
本文介绍了如何创建一个扩展具有输入验证的`int`基类的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个扩展 int 基类的类,以便该对象本身是一个整数(即,您直接对其进行设置和读取) ,但也具有输入验证功能-例如,仅允许给定范围。

I'd like to make a class that extends the int base class, so that the object itself is an integer (i.e. you set it and read from it directly), but also has input validation - for example, only allow a given range.

根据我的研究, __ init __ 方法,因此我不确定如何执行此操作。我也不清楚您如何访问对象的值(即分配给它的实际整数)或如何在类中修改该值。我看到了扩展任何基类(字符串,浮点数,元组,列表等)的相同问题。

From what I have researched, the __init__ method is not called when you extend normal base classes, so I'm not sure how to do this. I'm also not clear on how you access the value of the object (i.e. the actual integer assigned to it) or modify that value from within the class. I see the same issue extending any base class (string, float, tuple, list, etc.).

如果我可以使用 __ init __ 就像这样:

If I could use __init__ it would be something like:

class MyInt(int):
    def __init__(self, value):
        if value < 0 or value > 100:
            raise ValueError('MyInt objects must be in range 0-100, value was {}'.format(value))
        self = value

如何验证进入扩展的int类的新值?

How can I validate new values coming into my extended int class?

推荐答案

在这种情况下,您实际上不必覆盖 __ new __ 。创建对象后,将调用 __ init __ ,您可以检查它是否在范围内。

You don't actually have to override __new__ in this case. After the object is created, __init__ will be called, and you can check if it is in range or not.

class MyInt(int):
    def __init__(self, x, **kwargs):
        if self < 0 or self > 100:
            raise ValueError('MyInt objects must be in range 0-100, value was {}'.format(value))

您可以覆盖 __ new __ 以在 MyInt(...)返回新对象。

You can override __new__ to raise the exception before MyInt(...) returns the new object.

class MyInt(int):
    def __new__(cls, *args, **kwargs):
        x = super().__new__(cls, *args, **kwargs)  # Let any value error propagate
        if x < 0 or x > 100:
            raise ValueError('MyInt objects must be in range 0-100, value was {}'.format(value))
        return x

您可能想尝试在调用 super()的之前验证参数。__new __ ,但严格来说,这与其他课程的配合不好。

You might want to try to validate the argument before calling super().__new__, but strictly speaking, that's not playing well with other classes.

这篇关于如何创建一个扩展具有输入验证的`int`基类的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆