以正确的方式在 setter 和构造函数中重用验证逻辑 [英] Reusing validation logic in setter and constructor the right way

查看:26
本文介绍了以正确的方式在 setter 和构造函数中重用验证逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自定义 setter 属性的类来执行验证.我也希望能够将该属性作为构造函数参数传递,并从构造函数调用 setter 以重用验证逻辑:

class Part(object):def __init__(self, pn):# self._pn = 无self.pn = pn@财产def pn(self):返回 self._pn@pn.setterdef pn(self, value):如果类型(值)!= str:raise Exception("零件编号必须是字符串")self._pn = value # 警告在这里

在最后一行,PyCharm 给出了这个警告:

<块引用>

实例属性 _pn 定义在 __init__ 之外

如果我在构造函数中取消注释 self._pn = None 那么警告就会消失,但我不喜欢它,因为它是毫无意义的代码:如果引发异常,无论如何都不会创建对象,那么设置初始值有什么意义?

这是 PyCharm/工具的缺点,还是我做错了?有没有更好的方法来实现相同的目标,没有警告,没有毫无意义的代码,以 DRY 方式?

解决方案

PyCharm 在这里没有错.该警告告诉您正在运行时在对象上创建变量.

此警告的目的是提醒您您可能拼错了变量的名称,因为在编写 python 时可能会发生这种情况.

实际上,我认为您编写此类的方式确实不是编写 Python 的正确方式,因为 EXPLICIT 优于 IMPLICIT(在您的本地 Python 解释器中键入import zen").

请记住,以 _ 开头的变量表示仅当您知道自己在做什么时才使用."

I have a class with a property with a custom setter to perform validation. I would like to be able to pass the property as a constructor parameter too, and call the setter from the constructor to reuse the validation logic:

class Part(object):
    def __init__(self, pn):
        # self._pn = None
        self.pn = pn

    @property
    def pn(self):
        return self._pn

    @pn.setter
    def pn(self, value):
        if type(value) != str:
            raise Exception("Part number must be a string")
        self._pn = value  # warning here

On the last line, PyCharm gives this warning:

Instance attribute _pn defined outside __init__ 

If I uncomment the self._pn = None in the constructor then the warning goes away, but I don't like it, because it's pointless code: if an exception is raised, an object won't be created anyway, so what's the point setting an initial value?

Is this is a shortcoming of PyCharm / tooling, or am I doing it wrong? Is there a better way to achieve the same, without warnings, without pointless code, in a DRY way?

解决方案

PyCharm is not wrong here. The warning is telling you that you're creating a variable, in runtime, on the object.

The intention of this warning is to alert you that you might have misspelled a variable's name, since this is something that might happen when writing python.

I actually think the way you're writing this class is indeed not the right way to write python, since EXPLICIT is better than IMPLICIT (type "import zen" into your local python interpreter).

Remember, variables that start with _ mean "only use if you know what you're doing."

这篇关于以正确的方式在 setter 和构造函数中重用验证逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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