Object string representation in Python/IPython shell

我怕爱的太早我们不能终老 提交于 2019-12-23 02:53:17

问题


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


回答1:


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)




回答2:


I believe you could change Month's str to this:

def __str__(self):
  return self.dateobj.strftime("%m/%d/%y")

so it would access the date object and output it with the format you want Edit: Also, as already posted, you can make the repr method and just make it point to the str so you always get the same format




回答3:


def __str__(self):
    return self.dateobj.strftime("%Y-%m-%d")

though you could already output the date object's details by d.strftime("%Y-%m-%d")



来源:https://stackoverflow.com/questions/35295601/object-string-representation-in-python-ipython-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!