Python / IPython shell中的对象字符串表示形式 [英] Object string representation in Python/IPython shell
问题描述
我有一个友好的月课,我喜欢返回一个丑陋的机器人友好的字符串:
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>
我想要 m
code> 2010年1月31日。我尝试使用 unicode
和 str
,就像在django中,没有骰子:
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
对于 d
对象,它不实现unicode,而是字符串。 str
和ipython返回不匹配。我会为此打开一个单独的问题。我如何使我的python类显示对用户有用的东西? Terima kasih
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
推荐答案
您的真实问题是,Python 3 shell和IPython都调用<$ c $对于您的对象,c> repr 不 str
以下是一段代码片段:
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
如果没有定义 __ repr __
,IPython将简单地输出沿着< __ main__.Car在0x7f05841b1350>
而不是退回到 __ str __
。
Without the __repr__
defined, IPython would simply output something along <__main__.Car at 0x7f05841b1350>
instead of falling back to __str__
.
除非你明确地调用 str(car)
或 print(car)
,其中 __ str __
将被使用。
Unless you e.g. explicitly call str(car)
or print(car)
, in which the __str__
will be used.
所以,你应该定义一个 __ repr __
。
So, you should define a __repr__
in the object.
目前为止,
__ str __
这个 __ repr __
在Python 3或任何东西中替换 __ str __
,但 __ str __
只返回对象的可读取,而 __ repr __
是一个更完整的无歧义表示(甚至可以从 __repr __
输出)
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)
这篇关于Python / IPython shell中的对象字符串表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!