# default __repr__
>>> random.choice(Unit.get_all())
<module.Unit object at 0x10cff0550>
#After changing the definition__repr__
>>> random.choice(Unit.get_all())
Dragon Mermaid[ID:2001]
The value of __repr__
is also displayed in the error log, which is convenient for debugging.
'self' <Player: id: 123456 name: [Fishman] Orca Spycy Lv: 99>
python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
class BaseRepr(object):
id = 12345
name = 'Hinata Crab Zou'
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__
Execution result
>>>python test.py
<__main__.DefaultRepr object at 0x1086018d0> DefaultRepr
<__main__.DefaultReprOverWrite object at 0x1086018d0> DefaultReprOverWrite
Hinata Crab Zou[ID:12345] CustomRepr
__str__
and __unicode__
python
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())
Execution result
>>>python test.py
str: __str__
unicode: __unicode__
__str__
and __unicode__
python
class CustomRepr(BaseRepr):
def __repr__(self):
return '{}[ID:{}]'.format(self.name, self.id)
print 'str:', str(CustomRepr())
print 'unicode:', unicode(CustomRepr())
Execution result
>>>python test.py
str:Hinata Crab Zou[ID:12345]
unicode:Hinata Crab Zou[ID:12345]
Python Reference Manual Python str versus unicode Difference between str and repr in Python Hyuga Crab Zou
Recommended Posts