__getattribute__
Python のクラスと__setattr__
メソッドをオーバーライドしたいと考えています。私の使用例は通常のものです。処理したい特別な名前がいくつかあり、それ以外はデフォルトの動作が必要です。について__getattribute__
は、 を上げるだけでデフォルトの動作を要求できるようですAttributeError
。しかし、どうすれば同じことを達成でき__setattr__
ますか? これは、不変フィールド「A」、「B」、および「C」を持つクラスを実装する簡単な例です。
class ABCImmutable(SomeSuperclass):
def __getattribute__(self, name):
if name in ("A", "B", "C"):
return "Immutable value of %s" % name
else:
# This should trigger the default behavior for any other
# attribute name.
raise AttributeError()
def __setattr__(self, name, value):
if name in ("A", "B", "C"):
raise AttributeError("%s is an immutable attribute.")
else:
# How do I request the default behavior?
???
疑問符の代わりに何が入りますか? 古いスタイルのクラスでは、答えは明らかself.__dict__[name] = value
に でしたが、ドキュメントによると、新しいスタイルのクラスではこれが間違っていることが示されています。