[PYTHON] Programming for humans with a well-defined __repr__

# 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>

Verify implementation of repr

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

Also verify the behavior of __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__

If you do not define __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]

reference

Python Reference Manual Python str versus unicode Difference between str and repr in Python Hyuga Crab Zou

Recommended Posts

Programming for humans with a well-defined __repr__
Try programming with a shell!
I made a competitive programming glossary with Python
Media programming with Raspberry Pi (preparation for audio)
Prepare a programming language environment for data analysis
Get a ticket for a theme park with python
Create a LINE BOT with Minette for Python
Procedure for creating a LineBot made with Python
Create a dashboard for Network devices with Django!
Commands for creating a python3 environment with virtualenv
I made a window for Log output with Tkinter
Build a python environment for each directory with pyenv-virtualenv
Create a Layer for AWS Lambda Python with Docker
I tried a simple RPA for login with selenium
Building a Python environment for programming beginners (Mac OS)
Tips for opening a scene with a broken reference with a script
Build a Django environment for Win10 (with virtual space)
Programming with your smartphone anywhere! (Recommended for C / Python)
Asynchronous programming with libev # 2
3. 3. AI programming with Python
A4 size with python-pptx
Python programming with Atom
Competitive programming with python
Shader programming with pyOpenGL
Asynchronous programming with libev
Linear Programming with PuLP
Decorate with a decorator
Programming with Python Flask
Asynchronous programming with libev # 3
[Memo] Build a development environment for Django + Nuxt.js with Docker
Recommendations for django, wagtail ~ Why develop a website with python ~
Create a child account for connect with Stripe in Python
Experiment to make a self-catering PDF for Kindle with Python
Installation procedure for Python and Ansible with a specific version
I made a resource monitor for Raspberry Pi with a spreadsheet
A sample for drawing points with PIL (Python Imaging Library).
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Create a pixel art of Levi Captain with Python programming!
(For beginners) Try creating a simple web API with Django
[For beginners] A word summary of popular programming languages (2018 version)
Library for specifying a name server and dig with python
Turn an array of strings with a for statement (Python3)
Create a social integration API for smartphone apps with Django
[Python] Create a screen for HTTP status code 403/404/500 with Django