如何使用@属性装饰器来限制列表中的值

How to use @property decorator to restrict values inside a list

我是 python 的新手。所以如果我写错了,欢迎指正。

我创建了一个新的 class say ClassA,它有一个属性 modified,它是一个列表。

class最初是这样的:

class ClassA:
        def __init__(self):
            self.modified = []

我希望在此列表中添加(或修改)的元素首先通过检查。例如。我只想要此列表中格式为 YYYY-MM-DD 的日期。所以我认为 @propoerty 装饰器可以做一些工作。我按以下方式使用它:

class ClassA:

        def __init__(self):
            self._modified = []

        @property
        def modified(self):
            return getattr(self, "_modified")

        @modified.setter
        def modified(self, value):
            if not isinstance(value, list):
                raise TypeError("value passed must be a list")
            else:
                modified_list = []
                for item in value:
                    if isinstance(item, str):
                        result = performValidationCheck(item)
                        if not result:
                            raise ValueError("date format incorrect")
                        else:
                            modified_list.append(date.getDateAsString())
                    else:
                        raise TypeError("%s must be of type string")
                self._modified = modified_list

        def add_modified_date(self, date):
            if not isinstance(date, str):
                raise TypeError("date passed must be a string")
            result = performValidationCheck(date)
            if not result:
                raise ValueError(libsbml.OperationReturnValue_toString(result))
            self._modified.append(date)

但是,我仍然可以使用 classA.modified[index] 更改 modified 列表中条目的值。甚至 append 函数也在这个列表上工作。

我实现了performValidationCheck()功能,这里不关心

有人可以帮我解决这个问题吗?

However, I am still able to change the values of entries inside the modified list by using classA.modified[index]. Even the append function is also working on this list.However, I am still able to change the values of entries inside the modified list by using classA.modified[index]. Even the append function is also working on this list.

当然可以。 @property 仅控制获取/设置对象的属性。如果在属性上设置的对象是可变的,它什么也做不了。

Can someone help me with how should I proceed with this?

要么使用自定义的类似列表的集合(一个 MutableSequence)来动态验证它的值,要么使用一个 tuple(基本上是一个不可变的列表),这样调用者将无法就地修改它。