基本的には Python Language Reference の "3.4 Special method names" を参照。但し "3.4.2 Customizing attribute access" 以下と "3.4.3 Customizing class creation", "3.4.8 Coercion rules" は難しいので後回し。
とりあえずぱっと見で分かりやすい基本的な特殊メソッド(__repr__, __str__, __len__, __nonzero__, __call__)のオーバーライド例を試してみました。__init__ については省略。
なお、"__del__"については Effective Python Programming の63Pに "__del__ is not your friend" とあるので、避けておく。
__del__ often considered harmful
- C++/Java-ism
- __del__ breaks garbage collector
- non-deterministic
- doesn't always get called usefully when Python is exiting
- use a weakref in some cases
とのこと。
コードピース(t_basic_specialattrs.py) :
class C(object):
def __repr__(self):
return 'repr() is called.'
def __str__(self):
return 'str() is called.'
def __len__(self):
print 'len() is called.'
return 100
def __nonzero__(self):
print 'convert to boolean.'
return False
def mycall(self):
print 'this is callable object.'
return None
c = C()
print repr(c)
print str(c)
print len(c)
print bool(c)
C.__call__ = mycall
print c()
結果:
> python t_basic_specialattrs.py repr() is called. ... repr(c) str() is called. ... str(c) len() is called. ... len(c) 100 convert to boolean. ... bool(c) False this is callable object. ... c() None
なお基底クラスの特殊メソッドも呼びたい場合には、superやobject経由になります。
class C(object):
def __repr__(self):
print 'repr() is called.'
return object.__repr__(self)
def __str__(self):
print 'str() is called.'
return object.__str__(self)
こんな感じにもできます。
# repr(c) : repr() is called. <__main__.C object at 0x00AF8830>
# str(c) : str() is called. repr() is called. <__main__.C object at 0x00AF8830>
デフォルトのstr()はrepr()にバイパスされるみたいです。