在我的代码(Python)中,我有一个定义如下的类:

class Properties:

    def __init__(self,**kwargs):
        self.otherproperty = kwargs.get("otherproperty")
        self.channel = kwargs.get("channel")

        if self.channel not in "A":
            print("bad channel input - it should be A")
        pass

在代码的其余部分中,我在不同的位置计算各种属性,并将其添加到该类的实例中:

prop = Properties()
prop.channel="B"
#lots of calculations here
prop.otherproperty= "not a channel"

但是当我这样做时,我得到一个错误:TypeError: 'in <string>' requires string as left operand, not NoneType 我已经通过以下方式解决了问题,新属性得到了很好的验证,并且用户被告知prop.channel应该是不同的:

prop = Properties(otherproperty = "not a channel",channel="B")

但由于几个原因,以这种方式定义prop个对象将是不方便的.

那么,当我逐步添加对象的属性时,如何验证它们呢?这种循序渐进的物体建筑是如何专业命名的?

推荐答案

您可以使用Python descriptors为频道属性定义自定义设置器:

class Properties:
    def __init__(self, **kwargs):
        self.otherproperty = kwargs.get("otherproperty")
        self._channel = None  # Private attribute for channel

    @property
    def channel(self):
        return self._channel

    @channel.setter
    def channel(self, value):
        if value not in "A":
            raise ValueError("Bad channel input, it must be a substring of 'A'")
        self._channel = value

示例用法如下:

prop = Properties()
prop.channel = "B"  # Raises ValueError

这种逐渐向对象添加属性的方法可以称为"延迟对象初始化",如果您希望在创建对象之前避免长时间的计算,这种方法很有用.

附注:如果设置为prop.channel = "",上面的代码不会引发错误.因此,如果这是意外行为,您可能希望将验证更改为if value != "A":.

Python相关问答推荐

Polars比较了两个预设-有没有方法在第一次不匹配时立即失败

为什么符号没有按顺序添加?

聚合具有重复元素的Python字典列表,并添加具有重复元素数量的新键

用Python解密Java加密文件

django禁止直接分配到多对多集合的前端.使用user.set()

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

将pandas导出到CSV数据,但在此之前,将日期按最小到最大排序

为什么numpy. vectorize调用vectorized函数的次数比vector中的元素要多?

使用Python从rotowire中抓取MLB每日阵容

Matplotlib中的字体权重

导入错误:无法导入名称';操作';

在Python中从嵌套的for循环中获取插值

为用户输入的整数查找根/幂整数对的Python练习

有没有办法在不先将文件写入内存的情况下做到这一点?

如何写一个polars birame到DuckDB

try 在单个WITH_COLUMNS_SEQ操作中链接表达式时,使用Polars数据帧时出现ComputeError

关于数字S种子序列内部工作原理的困惑

将鼠标悬停在海运`pairplot`的批注/高亮显示上

将时间序列附加到数据帧

如何定义一个将类型与接收该类型的参数的可调用进行映射的字典?