本文介绍了在python中的现有内置类方法中添加装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个列表的类,每当将某些内容添加到一个列表中时,我都需要触发对实例状态的更改.我在下面创建了一个简单的演示类,以尝试演示我正在尝试做的事情.

I've got a class which contains a number of lists where whenever something is added to one of the lists, I need to trigger a change to the instance's state. I've created a simple demonstration class below to try to demonstrate what I'm trying to do.

假设我有一个这样的课程:

Suppose I have a class like this:

 class MyClass:
     added = False

     def _decorator(self, f):
         def func(item):
             added = true
             return f(item)
         return func

     def __init__(self):
         self.list = [1, 2, 3]
         self.list.append = self._decorator(self.list.append)

由于内置了列表,因此无法更改它的.append方法

Since a list is built in, I cannot change it's .append method

cls = MyClass() #gives me an AttributeError since '.append' is readonly

理想情况下,我可以执行以下操作:

Ideally, I could do the following:

cls = MyClass()
cls.list.append(4)
cls.added #would be true

我应该怎么做?子类化 list 会允许我以这种方式更改其行为吗?如果是这样,我将如何在不更改方法签名的情况下传递类的状态?

How should I go about this? Would subclassing list allow me to change it's behavior in this way? If so, how would I pass in the class's state without changing the methods signature?

谢谢!

推荐答案

您,因此子类化是唯一的方法(实际上是更好,更干净的恕我直言).我会选择这样的东西:

You cannot monkey-patch builtins, so subclassing is the only way (and actually better and cleaner IMHO). I'd go for something like this:

class CustomList(list):

  def __init__(self, parent_instance, *args, **kwargs):
    super(CustomList, self).__init__(*args, **kwargs)
    self.parent_instance = parent_instance

  def append(self, item):
      self.parent_instance.added = True
      super(CustomList, self).append(item)


class MyClass(object):
    added = False

    def __init__(self):
        self.list = CustomList(self, [1,2,3])


c = MyClass()
print c.added  # False
c.list.append(4)
print c.added  # True

这篇关于在python中的现有内置类方法中添加装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 22:22