LoginSignup
29
29

More than 5 years have passed since last update.

__repr__をしっかり定義して人間のためのプログラミング

Last updated at Posted at 2015-10-23
# 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
日向蟹造

29
29
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
29