开发者

Python instance string in a list

开发者 https://www.devze.com 2023-02-19 00:28 出处:网络
I have a simple class in python that has a __str__() function. Like this: class Foo(object): def __init__():

I have a simple class in python that has a __str__() function. Like this:

class Foo(object):
   def __init__():
       self.name = 'something'

   def __str__():
       return self.name

My real class does more than that, but this is an e开发者_如何转开发xample.

So then I do this:

a = Foo()
b = Foo()

print a
print b
print [a,b]

Except this prints:

something
something
[<Foo object at HexString>,<Foo object at HexString>]

Why is the printed version in the list not printing the str name of the instance and is there an easy way to get it to?

I've tried to see if __unicode__ is different and it is not.


You need to add a __repr__ method as well:

class Foo(object):
   def __repr__(self):
       return str(self)

   def __str__(self):
       return self.name

See this question about the difference between __str__ and __repr__.

Note also that you're missing the self arguments to the methods in your sample code ;-)


The string representation of the list actually calls __repr__() on every item -- so just overwrite that method.

0

精彩评论

暂无评论...
验证码 换一张
取 消