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

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

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

Python / codepiece / 特殊メソッド / 0.基本の特殊メソッド (v1)
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__ については省略。

コードピース(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()にバイパスされるみたいです。



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