Python中的包装类

6 投票
1 回答
23775 浏览
提问于 2025-04-17 15:12

我想要一个包装类,它的行为和它所包装的对象完全一样,只是在某些特定的方法上进行添加或覆盖。

我现在的代码是这样的:

# Create a wrapper class that equips instances with specified functions
def equipWith(**methods):

  class Wrapper(object):
    def __init__(self, instance):
      object.__setattr__(self, 'instance',instance)

    def __setattr__(self, name, value):
      object.__setattr__(object.__getattribute__(self,'instance'), name, value)

    def __getattribute__(self, name):
      instance = object.__getattribute__(self, 'instance')

      # If this is a wrapped method, return a bound method
      if name in methods: return (lambda *args, **kargs: methods[name](self,*args,**kargs))

      # Otherwise, just return attribute of instance
      return instance.__getattribute__(name)

  return Wrapper

为了测试这个,我写了:

class A(object):
  def __init__(self,a):
    self.a = a

a = A(10)
W = equipWith(__add__ = (lambda self, other: self.a + other.a))
b = W(a)
b.a = 12
print(a.a)
print(b.__add__(b))
print(b + b)

在最后一行时,我的解释器报错了:

Traceback (most recent call last):
  File "metax.py", line 39, in <module>
    print(b + b)
TypeError: unsupported operand type(s) for +: 'Wrapper' and 'Wrapper'

这是为什么呢?我该如何让我的包装类按我想要的方式工作呢?

1 个回答

7

看起来你想要的功能只能通过新式对象和一些特别的方法来实现。你可以参考这个链接、这个博客文章和这个文档

简单来说,这些“特殊”的函数可以让新式对象在查找时更高效。

撰写回答