Python Tips and Tricks
# __repr__ vs __str__
How a python Class is represented as a string also how is represented, when you interact with the object.Instead of building your own to-string conversion machinery you’ll be better off adding the __str__ and __repr__ “dunder” methods
to your class. They are the Pythonic way to control how objects are
converted to strings in different situations
Notes:
str = easy to read representation of the class
repr = unambiguos more ment for developers
Example
import datetime
date = datetime.date.today()
> str(date)
>'2017-07-11'
> repr(date)
'datetime.date(2017, 7, 11)'
****************************************************
How a python Class is represented as a string also how is represented, when you interact with the object.Instead of building your own to-string conversion machinery you’ll be better off adding the __str__ and __repr__ “dunder” methods
to your class. They are the Pythonic way to control how objects are
converted to strings in different situations
Notes:
str = easy to read representation of the class
repr = unambiguos more ment for developers
Example
import datetime
date = datetime.date.today()
> str(date)
>'2017-07-11'
> repr(date)
'datetime.date(2017, 7, 11)'
****************************************************
# The get() method on dicts # and its "default" argument name_for_userid = { 382: "Alice", 590: "Bob", 951: "Dilbert", } def greeting(userid): return "Hi %s!" % name_for_userid.get(userid, "there") >>> greeting(382) "Hi Alice!" >>> greeting(333333) "Hi there!"
Comentarios
Publicar un comentario