【问题标题】:Python 3.x - Run function before appending item to listPython 3.x - 在将项目附加到列表之前运行函数
【发布时间】:2016-05-09 02:37:30
【问题描述】:

在 Python 3.x 中,是否可以在将项目附加到列表之前运行函数?

我有一个从列表继承的类,还有一些额外的自定义函数。我希望对添加到此列表的任何元素的数据执行一系列检查。如果添加的元素不符合某些条件,列表将引发错误。

class ListWithExtraFunctions(list):

   def __beforeappend__(self):

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

【问题讨论】:

    标签: python list class python-3.x inheritance


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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")
      

      【讨论】:

        猜你喜欢
        • 2016-08-25
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        • 2016-11-04
        • 1970-01-01
        • 2018-02-12
        • 2023-03-31
        • 2011-05-15
        相关资源
        最近更新 更多