简体   繁体   English

在 python 中获取设置器状态

[英]Get setter status in python

I am looking to return a status when setting an instance variable.我希望在设置实例变量时返回一个状态。 This return value will either indicate that the value was set or the value was invalid.此返回值将指示该值已设置或该值无效。 For example:例如:

class C():
    def __init__(self):
        self._attr = 1

    @property
    def attr(self):
        return self._attr

    @attr.setter
    def attr(self, val):
        if val < 10:
            self._attr = val
            return 'value set'
        else:
            return 'value must be < 10'

status = C().attr = 11 # should return failed
status = C().attr = 9 # should return worked

Adding return values to all my setters would be time-consuming and seems to be bad practice.将返回值添加到我所有的设置器会很耗时,而且似乎是不好的做法。 Is there a better way to get a status from a setter?有没有更好的方法从二传手那里获得状态?

The other solution I thought of was to write a "setSetter()" function that calls attr = val then checks if attr == val (which works like a status variable).我想到的另一个解决方案是编写一个“setSetter()”function,它调用attr = val然后检查attr == val (它像一个状态变量一样工作)。 However, it seems like there should be a better method.但是,似乎应该有更好的方法。

Also, if there is a better way to structure the flow control so that attributes aren't set to invalid values I'm open to changing my strategy.此外,如果有更好的方法来构建流控制,以便属性不会设置为无效值,我愿意改变我的策略。

Thanks in advance for the help!在此先感谢您的帮助!

The standard way to indicate failure in Python and/or prevent code from reaching an invalid state is to raise an exception to indicate you've encountered a situation where you can't continue execution.指示 Python 中的故障和/或防止代码到达无效的 state 的标准方法是raise异常以指示您遇到了无法继续执行的情况。 This doesn't require you to modify the return type:这不需要您修改返回类型:

    @attr.setter
    def attr(self, val: int) -> None:
        if val < 10:
            self._attr = val
        else:
            raise ValueError('value must be < 10')
try:
    C().attr = 9  # works
    C().attr = 11 # raises ValueError and goes to nearest matching except
    C().attr = 13 # is never executed
except ValueError as e:
    print(e)      # prints 'value must be < 10'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM