如何使用__str__和__repr__? [英] how to use __str__ and __repr__?

查看:72
本文介绍了如何使用__str__和__repr__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,有没有人知道如果没有__str__方法会打印什么?

我试图覆盖__repr__。如果有人可以给我一些建议

那就太棒了。


我已经定义了类似lisp的链表类作为列表的子类。

__iter__似乎按照我想要的方式工作,通过遍历链接,

和__repr__似乎适合某些人而不是其他人。


基本思路是将[1,2,3,4]这样的列表转换为

[1,[2,[3,[4,nil] ]]],因此允许我将一个新元素

非破坏性地推送到列表的开头;例如


x = seq2pair([3,4,5]) - > [3,[4,[5,nil]]]

y = x.cons(2) - > [2,[3,[4,[5,nil]]]

z = y.cons(1) - > [1,[2,[3,[4,[5,nil]]]]

对于el中的
:#iterates elt = 1,elt = 2,elt = 3 ...

通过


我很想知道如何定义__repr__或__str__

方法,以便它能够以打印的方式打印所有内容

通常可以正常工作,除了我班级的实例打印

特别。我想打印[1,[2,[3,[4,[5,nil]]]]

简单作为空格分隔列表。它大部分时间都有效。

- > (1 2 3 4 5)


另一个问题是,是否有办法将一个

空列表[]推广到一个实例?


班对(列表):


def __iter __(个体经营):

而自我:

产生self.car()

self = self.cdr()

def __repr __(个体经营):

中= " .join([substr .__ str __()for substr in self])

return"(" + middle +")"


#x =(cons x l_y)

#==> x = l_y.cons(x)

def cons(self,car):

new =一对()

new.append(car )

new.append(个体经营)

返回新品

def车(个体经营):

如果自己:

返回自我[0]

返回无

def cdr(个体经营):

if len(self)< 2:

return nil

return self [1]


nil = Pair ()

#[1,2,3] - > [1,[2,[3,nil]]]

def seq2pair(seq):

new = Pair()

for index在xrange(len(seq),0,-1):

new = new.cons(seq [index - 1])

返回新


mylist = seq2pair([1,2,3,4,5])

打印mylist#正确打印 - > (1 2 3 4 5)

mylist2 = seq2pair([11.1,21.1,31.1,41.1,mylist])

打印mylist2

#正确打印 - > (11.1 21.1 31.1 41.1(1 2 3 4 5))


另一类:

通过


打印另一个()#prints - > < __ main __。另一个实例在0x8132b64>


#???????????????????????????? ??????????

打印seq2pair([another(),另一个()])#FAILS

#??????回溯(最近期)
回溯(最近一次)最后拨打):

文件" xyz.py",第52行,在?

打印seq2pair([another(),another()])

文件" xyz.py",第13行,在__repr__

返回"(" +"" .join([substr .__ str __()for substr in self] )+")"

AttributeError:另一个实例没有属性''__str__''

解决方案

< blockquote> Jim Newton写道:

大家好,有没有人知道如果没有__str__方法会打印什么?




来自 http://docs.python.org/ref/custo上的文档mization.html


__repr __(self)


由repr()内置函数和字符串转换调用

(反向引号)来计算

对象的官方'''字符串表示。 ....如果一个类定义__repr __()而不是__str __(),那么

__repr __()也用于
$ b的非正式'''字符串表示该类的$ b实例是必需的。


这有帮助吗?


我不明白你在尝试什么要做,但是

问题是,当你定义类''另一个''

时,下面的行没有意义:

middle =" " .join([substr .__ str __()for substr in self])

另一个实例没有__str__方法

定义(例如,这是一个空洞的课程)。你所有的其他

测试都有一个具有__str__方法的类

,因为它是从基类列表中继承的。


你可以尝试:


class another(list):

pass


Larry Bates

Syscon,Inc。


" Jim Newton" <ジ*** @ rdrop.com>在留言中写道

新闻:2i ************ @ uni-berlin.de ...

大家好,有谁知道是什么如果没有__str__方法会打印吗?
我试图覆盖__repr__。如果有人可以给我一些建议
它会很棒。

我已经定义了一个类似于lisp的链表类作为列表的子类。
__iter__似乎按照我的意愿工作,通过遍历链接,
和__repr__似乎适合某些人而不是其他人。

基本的想法是如[1, 2,3,4]转换为
[1,[2,[3,[4,nil]]],这样我就可以非破坏性地将一个新元素推到(缺点)列表的开头;例如

x = seq2pair([3,4,5]) - > [3,[4,[5,nil]]]
y = x.cons(2) - > [2,[3,[4,[5,nil]]]
z = y.cons(1) - > [1,[2,[3,[4,[5,nil]]]]
对于el中的z:#iterates elt = 1,elt = 2,elt = 3 ...
传递

我很想知道如何定义__repr__或__str__
方法,以便它能够以打印方式正常工作的方式打印所有内容,除了实例我的班级被打印
特别。我想打印[1,[2,[3,[4,[5,nil]]]]
简单作为空格分隔列表。它大部分时间都有效。
- > (1 2 3 4 5)

另一个问题是,是否有办法将
空列表[]推广到一对实例?

类对(列表):

def __iter __(自我):
而self:
产生self.car()
self = self.cdr()

def __repr __(self):
middle =" " .join([substr .__ str __()for substr in self])
return"(" + middle +")"

#x =(cons x l_y )
#==> x = l_y.cons(x)
def cons(self,car):
new = Pair()
new.append(car)
new.append(self)<返回新的

def车(自我):
如果自我:
返回自我[0]
返回nil

def cdr(self):
如果len(self)< 2:
返回nil
返回自己[1]

nil = Pair()

#[1,2,3] - > [1,[2,[3,nil]]]
def seq2pair(seq):
new = Pair()
for xrange(len(seq),0,-1) ):
new = new.cons(seq [index - 1])
返回新的

mylist = seq2pair([1,2,3,4,5])
打印mylist#正确打印 - > (1 2 3 4 5)

mylist2 = seq2pair([11.1,21.1,31.1,41.1,mylist])
打印mylist2
#correct prints - > (11.1 21.1 31.1 41.1(1 2 3 4 5))
另一类:
打印
打印另一个()#prints - > < __ main __。另一个实例在0x8132b64>

#????????????????????????????? ????????
打印seq2pair([另一个(),另一个()])#FAILS
#??????????????????跟踪(最近一次调用最后一次):
文件xyz.py,第52行,在?
打印seq2pair([another(),another()])
文件xyz.py,第13行,在__repr__
return"(" + " .join([substr .__ str __()for substr in self])+
")" AttributeError:另一个实例没有属性''__str __''



感谢您的回复,

i期待class().__ str__ ()

来评估字符串"< __ main __。另一个实例位于0x8132b64>"

因为那个打印用class()做了什么。

但是它没有。


为什么print class()没有给出与class()相同的错误.__ str __()?

那是我不理解的。


-jim

Larry Bates写道:

我不是了解你想要做什么,但问题是当你定义类''另一个'时
以下行没有意义:

middle = " " .join([substr .__ str __()for substr in self])

另一个实例没有__str__方法定义(例如它是空的类)。你所有的其他测试都有一个确实有__str__方法的类,因为它是从基类列表中继承的。

你可以尝试:
另一个(列表):


拉里贝茨
Syscon,Inc。

Jim Newton <ジ*** @ rdrop.com>在消息中写道
新闻:2i ************ @ uni-berlin.de ...

大家好,有谁知道是什么如果没有__str__方法会打印吗?
我试图覆盖__repr__。如果有人可以给我一些建议
它会很棒。

我已经定义了一个类似于lisp的链表类作为列表的子类。
__iter__似乎按照我的意愿工作,通过遍历链接,
和__repr__似乎适合某些人而不是其他人。

基本的想法是如[1, 2,3,4]转换为
[1,[2,[3,[4,nil]]],这样我就可以非破坏性地将一个新元素推到(缺点)列表的开头;例如

x = seq2pair([3,4,5]) - > [3,[4,[5,nil]]]
y = x.cons(2) - > [2,[3,[4,[5,nil]]]
z = y.cons(1) - > [1,[2,[3,[4,[5,nil]]]]
对于el中的z:#iterates elt = 1,elt = 2,elt = 3 ...
传递

我很想知道如何定义__repr__或__str__
方法,以便它能够以打印方式正常工作的方式打印所有内容,除了实例我的班级被打印
特别。我想打印[1,[2,[3,[4,[5,nil]]]]
简单作为空格分隔列表。它大部分时间都有效。
- > (1 2 3 4 5)

另一个问题是,是否有办法将
空列表[]推广到一对实例?

类对(列表):

def __iter __(自我):
而self:
产生self.car()
self = self.cdr()

def __repr __(self):
middle =" " .join([substr .__ str __()for substr in self])
return"(" + middle +")"

#x =(cons x l_y )
#==> x = l_y.cons(x)
def cons(self,car):
new = Pair()
new.append(car)
new.append(self)<返回新的

def车(自我):
如果自我:
返回自我[0]
返回nil

def cdr(self):
如果len(self)< 2:
返回nil
返回自己[1]

nil = Pair()

#[1,2,3] - > [1,[2,[3,nil]]]
def seq2pair(seq):
new = Pair()
for xrange(len(seq),0,-1) ):
new = new.cons(seq [index - 1])
返回新的

mylist = seq2pair([1,2,3,4,5])
打印mylist#正确打印 - > (1 2 3 4 5)

mylist2 = seq2pair([11.1,21.1,31.1,41.1,mylist])
打印mylist2
#correct prints - > (11.1 21.1 31.1 41.1(1 2 3 4 5))
另一类:
打印
打印另一个()#prints - > < __ main __。另一个实例在0x8132b64>

#????????????????????????????? ????????
打印seq2pair([另一个(),另一个()])#FAILS
#??????????????????跟踪(最近一次调用最后一次):
文件xyz.py,第52行,在?
打印seq2pair([another(),another()])
文件xyz.py,第13行,在__repr__
return"(" + " .join([substr .__ str __()for substr in self])+



")"

AttributeError :另一个实例没有属性''__str __''





hi all, does anyone know what print does if there is no __str__ method?
i''m trying ot override the __repr__. If anyone can give me some advice
it would be great to have.

I have defined a lisp-like linked list class as a subclass of list.
The __iter__ seems to work as i''d like, by traversing the links,
and the __repr__ seems to work properly for somethings but not others.

The basic idea is that a list such as [ 1, 2, 3, 4] is converted to
[1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element
non-destructively onto the beginning of the list; e.g.

x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]]
y = x.cons(2) --> [ 2, [3, [4, [5, nil]]]
z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]]

for elt in z: # iterates elt=1, elt=2, elt=3 ...
pass

I would love to know how to define the __repr__ or __str__
method so that it is able to print everything the way print
normally works, except that instances of my class gets printed
special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]]
simple as a space seperated list. It works most of the time.
--> ( 1 2 3 4 5)

Another question is whether there is a way to promote an
empty list [] to an instance of Pair?

class Pair(list):

def __iter__(self):
while self:
yield self.car()
self = self.cdr()

def __repr__(self):
middle = " ".join( [ substr.__str__() for substr in self])
return "( " + middle + " )"

# x = (cons x l_y)
# ==> x = l_y.cons(x)
def cons(self, car):
new = Pair()
new.append(car)
new.append(self)
return new

def car(self):
if self:
return self[0]
return nil

def cdr(self):
if len(self)<2:
return nil
return self[1]

nil = Pair()
# [ 1, 2, 3] --> [1, [2, [3, nil]]]
def seq2pair(seq):
new = Pair()
for index in xrange( len(seq), 0, -1):
new = new.cons(seq[index - 1])
return new

mylist = seq2pair( [1,2,3,4,5])
print mylist # correctly prints --> ( 1 2 3 4 5)
mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist])
print mylist2
# correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) )

class another:
pass

print another() # prints --> <__main__.another instance at 0x8132b64>

# ????????????????????????????????????????
print seq2pair( [ another(), another() ]) # FAILS
# ????????????????????????????????????????

Traceback (most recent call last):
File "xyz.py", line 52, in ?
print seq2pair( [ another(), another() ])
File "xyz.py", line 13, in __repr__
return "( " + " ".join( [ substr.__str__() for substr in self]) + " )"
AttributeError: another instance has no attribute ''__str__''

解决方案

Jim Newton wrote:

hi all, does anyone know what print does if there is no __str__ method?



From the documentation at http://docs.python.org/ref/customization.html :

__repr__( self)

Called by the repr() built-in function and by string conversions
(reverse quotes) to compute the ``official'''' string representation of an
object. .... If a class defines __repr__() but not __str__(), then
__repr__() is also used when an ``informal'''' string representation of
instances of that class is required.

Does that help?


I don''t understand what you are trying to do, but
the problem is that when you define class ''another''
the following line doesn''t make sense:

middle = " ".join( [ substr.__str__() for substr in self])

The instance of another doesn''t have a __str__ method
defined (e.g. it''s an empty class). All of your other
tests have a class that does have a __str__ method
because it was inherited from the baseclass list.

You could try:

class another(list):
pass

Larry Bates
Syscon, Inc.

"Jim Newton" <ji***@rdrop.com> wrote in message
news:2i************@uni-berlin.de...

hi all, does anyone know what print does if there is no __str__ method?
i''m trying ot override the __repr__. If anyone can give me some advice
it would be great to have.

I have defined a lisp-like linked list class as a subclass of list.
The __iter__ seems to work as i''d like, by traversing the links,
and the __repr__ seems to work properly for somethings but not others.

The basic idea is that a list such as [ 1, 2, 3, 4] is converted to
[1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element
non-destructively onto the beginning of the list; e.g.

x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]]
y = x.cons(2) --> [ 2, [3, [4, [5, nil]]]
z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]]

for elt in z: # iterates elt=1, elt=2, elt=3 ...
pass

I would love to know how to define the __repr__ or __str__
method so that it is able to print everything the way print
normally works, except that instances of my class gets printed
special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]]
simple as a space seperated list. It works most of the time.
--> ( 1 2 3 4 5)

Another question is whether there is a way to promote an
empty list [] to an instance of Pair?

class Pair(list):

def __iter__(self):
while self:
yield self.car()
self = self.cdr()

def __repr__(self):
middle = " ".join( [ substr.__str__() for substr in self])
return "( " + middle + " )"

# x = (cons x l_y)
# ==> x = l_y.cons(x)
def cons(self, car):
new = Pair()
new.append(car)
new.append(self)
return new

def car(self):
if self:
return self[0]
return nil

def cdr(self):
if len(self)<2:
return nil
return self[1]

nil = Pair()
# [ 1, 2, 3] --> [1, [2, [3, nil]]]
def seq2pair(seq):
new = Pair()
for index in xrange( len(seq), 0, -1):
new = new.cons(seq[index - 1])
return new

mylist = seq2pair( [1,2,3,4,5])
print mylist # correctly prints --> ( 1 2 3 4 5)
mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist])
print mylist2
# correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) )

class another:
pass

print another() # prints --> <__main__.another instance at 0x8132b64>

# ????????????????????????????????????????
print seq2pair( [ another(), another() ]) # FAILS
# ????????????????????????????????????????

Traceback (most recent call last):
File "xyz.py", line 52, in ?
print seq2pair( [ another(), another() ])
File "xyz.py", line 13, in __repr__
return "( " + " ".join( [ substr.__str__() for substr in self]) + " )" AttributeError: another instance has no attribute ''__str__''



thanks for responding,
i was expecting class().__str__()
to evaluate to the string "<__main__.another instance at 0x8132b64>"
because that what print does with class().
but alas it does not.

why does print class() not give me the same error as class().__str__()?
that''s what i do not understand.

-jim
Larry Bates wrote:

I don''t understand what you are trying to do, but
the problem is that when you define class ''another''
the following line doesn''t make sense:

middle = " ".join( [ substr.__str__() for substr in self])

The instance of another doesn''t have a __str__ method
defined (e.g. it''s an empty class). All of your other
tests have a class that does have a __str__ method
because it was inherited from the baseclass list.

You could try:

class another(list):
pass

Larry Bates
Syscon, Inc.

"Jim Newton" <ji***@rdrop.com> wrote in message
news:2i************@uni-berlin.de...

hi all, does anyone know what print does if there is no __str__ method?
i''m trying ot override the __repr__. If anyone can give me some advice
it would be great to have.

I have defined a lisp-like linked list class as a subclass of list.
The __iter__ seems to work as i''d like, by traversing the links,
and the __repr__ seems to work properly for somethings but not others.

The basic idea is that a list such as [ 1, 2, 3, 4] is converted to
[1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element
non-destructively onto the beginning of the list; e.g.

x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]]
y = x.cons(2) --> [ 2, [3, [4, [5, nil]]]
z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]]

for elt in z: # iterates elt=1, elt=2, elt=3 ...
pass

I would love to know how to define the __repr__ or __str__
method so that it is able to print everything the way print
normally works, except that instances of my class gets printed
special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]]
simple as a space seperated list. It works most of the time.
--> ( 1 2 3 4 5)

Another question is whether there is a way to promote an
empty list [] to an instance of Pair?

class Pair(list):

def __iter__(self):
while self:
yield self.car()
self = self.cdr()

def __repr__(self):
middle = " ".join( [ substr.__str__() for substr in self])
return "( " + middle + " )"

# x = (cons x l_y)
# ==> x = l_y.cons(x)
def cons(self, car):
new = Pair()
new.append(car)
new.append(self)
return new

def car(self):
if self:
return self[0]
return nil

def cdr(self):
if len(self)<2:
return nil
return self[1]

nil = Pair()
# [ 1, 2, 3] --> [1, [2, [3, nil]]]
def seq2pair(seq):
new = Pair()
for index in xrange( len(seq), 0, -1):
new = new.cons(seq[index - 1])
return new

mylist = seq2pair( [1,2,3,4,5])
print mylist # correctly prints --> ( 1 2 3 4 5)
mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist])
print mylist2
# correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) )

class another:
pass

print another() # prints --> <__main__.another instance at 0x8132b64>

# ????????????????????????????????????????
print seq2pair( [ another(), another() ]) # FAILS
# ????????????????????????????????????????

Traceback (most recent call last):
File "xyz.py", line 52, in ?
print seq2pair( [ another(), another() ])
File "xyz.py", line 13, in __repr__
return "( " + " ".join( [ substr.__str__() for substr in self]) +



" )"

AttributeError: another instance has no attribute ''__str__''





这篇关于如何使用__str__和__repr__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆