Issue
I have a friendly month class I enjoy that returns an ugly robot friendly string:
In [3]: d = date(2010, 1, 31)
In [4]: m = Month(d)
In [5]: m
Out[5]: <dfa.date_range.Month at 0x7fb4d5793cc0>
I want m
to show something like 1-31-2010
. I try using unicode
and str
, just like in django, no dice:
class Month(object):
def __init__(self, dateobj):
self.dateobj = dateobj
# def __unicode__(self):
# return self.dateobj
def __str__(self):
return self.dateobj
@property
def first_day(self):
return self.dateobj.replace(day = 1)
@property
def last_day(self):
_, days_in_month = monthrange(self.dateobj.year, self.dateobj.month)
return self.dateobj.replace(day = days_in_month)
def date_range(self):
return self.first_day, self.last_day
For d
object, it doesn't implement unicode, but has string. The str
and ipython return don't match. I'll open a separate question for that. How can I make my python classes display something useful for the user? Terima kasih
Solution
Your real issue is that both Python 3 shell and IPython call repr
NOT str
on your object. Here's a snippet to play with to see:
In [1]: class Car(object):
...: def __str__(self):
...: return 'car str'
...: def __repr__(self):
...: return 'car repr'
...:
In [2]: car = Car()
In [3]: car
Out[3]: car repr
Without the __repr__
defined, IPython would simply output something along <__main__.Car at 0x7f05841b1350>
instead of falling back to __str__
.
Unless you e.g. explicitly call str(car)
or print(car)
, in which the __str__
will be used.
So, you should define a __repr__
in the object.
What purpose is
__str__
nowadays then?
It's not that __repr__
replaces __str__
in Python 3 or anything, but __str__
merely returns a readable reprentation of the object, while __repr__
is a more complete unambiguous representation (to the point where you can even reconstruct the object from the __repr__
output)
Answered By - bakkal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.