# default __repr__
>>> random.choice(Unit.get_all())
<module.Unit object at 0x10cff0550>
# 定義変更後の __repr__
>>> random.choice(Unit.get_all())
ドラゴン・マーメイド[ID:2001]
エラーログにも__repr__
の値が表記されるのでデバッグで便利
'self' <Player: id:123456 name:【魚人】オルカ・スパイシー Lv:99>
reprの実装を検証
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
class BaseRepr(object):
id = 12345
name = '日向蟹造'
class DefaultRepr(BaseRepr):
pass
class DefaultReprOverWrite(BaseRepr):
def __repr__(self):
return '<{0}.{1} object at {2}>'.format(
self.__module__, type(self).__name__, hex(id(self)))
class CustomRepr(BaseRepr):
def __repr__(self):
return '{}[ID:{}]'.format(self.name, self.id)
print DefaultRepr(), DefaultRepr.__name__
print DefaultReprOverWrite(), DefaultReprOverWrite.__name__
print CustomRepr(), CustomRepr.__name__
実行結果
>>>python test.py
<__main__.DefaultRepr object at 0x1086018d0> DefaultRepr
<__main__.DefaultReprOverWrite object at 0x1086018d0> DefaultReprOverWrite
日向蟹造[ID:12345] CustomRepr
__str__
と__unicode__
の挙動も検証する
class CustomRepr(BaseRepr):
def __repr__(self):
return '{}[ID:{}]'.format(self.name, self.id)
def __str__(self):
return '__str__'
def __unicode__(self):
return '__unicode__'
print 'str:', str(CustomRepr())
print 'unicode:', unicode(CustomRepr())
実行結果
>>>python test.py
str: __str__
unicode: __unicode__
__str__
と__unicode__
を定義しない場合
class CustomRepr(BaseRepr):
def __repr__(self):
return '{}[ID:{}]'.format(self.name, self.id)
print 'str:', str(CustomRepr())
print 'unicode:', unicode(CustomRepr())
実行結果
>>>python test.py
str: 日向蟹造[ID:12345]
unicode: 日向蟹造[ID:12345]
参考
Python リファレンスマニュアル
Python str versus unicode
Difference between str and repr in Python
日向蟹造