特にPython 2.6以降のクラスデコレータは、多くのメソッドをラップして「スーパークラスのインスタンスではなく、このクラスの型のインスタンスを返す」最も簡単な方法です。これは、他の人が示しているように、根本的な問題です(__str__
vsとの口論を超えて__repr__
、価値はありますが、問題を解決するものではありません;-)。
def returnthisclassfrom(specials):
specialnames = ['__%s__' % s for s in specials.split()]
def wrapit(cls, method):
return lambda *a: cls(method(*a))
def dowrap(cls):
for n in specialnames:
method = getattr(cls, n)
setattr(cls, n, wrapit(cls, method))
return cls
return dowrap
@returnthisclassfrom('and or xor')
class Hex(int):
def __repr__(self): return hex(self)
__str__ = __repr__
a = Hex(2345)
b = Hex(5432)
print a, b, a^b
Python 2.6 では、これは
0x929 0x1538 0x1c11
望んだ通りに。もちろん、デコレーターなどにメソッド名を追加することもできます。Python 2.5 に行き詰まっている場合は、装飾行 ( で始まる行) を削除し、@
代わりに使用します
class Hex(int):
def __repr__(self): return hex(self)
__str__ = __repr__
Hex = returnthisclassfrom('and or xor')(Hex)
ダニはエレガントではありませんが、同じくらい効果的です;-)
編集:コード内の「通常のスコープの問題」の発生を修正しました。