Python 3.x - 在将项目添加到列表之前运行函数

2024-09-30 19:20:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3.x中,是否可以在一个项被附加到列表之前运行一个函数?你知道吗

我有一个从列表继承的类,带有一些附加的自定义函数。我想对添加到此列表中的任何元素的数据执行一系列检查。如果添加的元素不符合某些条件,列表将引发错误。你知道吗

class ListWithExtraFunctions(list):

   def __beforeappend__(self):

      ... run some code ...
      ... perform checks ...
      ... raise error if checks fail ...

Tags: 数据函数runself元素列表def错误
2条回答

此选项与Vaultah编写的解决方案非常相似。它只使用“try…except”,允许您以某种方式处理异常。你知道吗

class Nw_list(list):


    def val_check(self, value):
        # Accepts only integer
        if type(value) == int:
            return value
        else:
            # Any other input type will raise exception 
            raise ValueError

    def append(self, value):
        try:
            # Try to append checked value
            super().append(self.val_check(value))                                      
        except ValueError:
            # If value error is raised prints msg
            print("You can append only int values")

如果value通过所有检查,则定义ListWithExtraFunctions.append并调用super().append(value)

class ListWithExtraFunctions(list):
    def append(self, value):
        if okay():
            return super().append(value)
        else:
            raise NotOkay()

相关问题 更多 >