home ホーム search 検索 -  login ログイン  | reload edit datainfo version cmd icon diff delete  | help ヘルプ

Python/codepiece/特殊メソッド/0.基本の特殊メソッド

Python/codepiece/特殊メソッド/0.基本の特殊メソッド

Python / codepiece / 特殊メソッド / 0.基本の特殊メソッド
id: 214 所有者: msakamoto-sf    作成日: 2009-03-21 19:04:39
カテゴリ: Python 

基本的には 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()にバイパスされるみたいです。



プレーンテキスト形式でダウンロード
現在のバージョン : 2
更新者: msakamoto-sf
更新日: 2009-03-21 23:21:17
md5:5bab265074321c783162d13210dec09f
sha1:d31e10a60fe45e07fe9262c7a8225cf456e16d70
コメント
コメントを投稿するにはログインして下さい。