5

いくつかの選択メソッドを追加または上書きすることを除いて、ラップするオブジェクトとまったく同じように動作するラッパー クラスが必要です。

私のコードは現在次のようになっています。

# 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'

どうしてこれなの?ラッパー クラスを希望どおりに動作させるにはどうすればよいですか?

4

1 に答える 1

7

とてつもない手段を講じた新しいスタイルのオブジェクトでのみ、あなたが望むことができるようです。https://stackoverflow.com/a/9059858/380231このブログ投稿、およびドキュメントを参照してください。

基本的に、「特別な」関数は、新しいスタイルのオブジェクトのルックアップ手順を短縮します。

于 2013-02-08T05:45:28.593 に答える