对象的python __str__

Sha*_*kan 22 python

在试图弄清楚BeautifulSoup是如何工作的时候,我顺便学会了这个__str__方法(我是python的新手).因此,如果我没有误解,那么该__str__方法有助于塑造如何打印出来的类的表示方式.例如:

class Foo:
    def __str__(self):
        return "bar"

>>> x = Foo()
>>> print x
bar
Run Code Online (Sandbox Code Playgroud)

对?所以断言我是对的,是否有可能覆盖__str__字典列表的方法?我的意思是说在Foo课你有:

class Foo:
   def __init__(self):
      self.l = [{"Susan": ("Boyle", 50, "alive")}, {"Albert": ("Speer", 106, "dead")}]
Run Code Online (Sandbox Code Playgroud)

现在有可能得到以下结果吗?

>>> x = Foo()
>>> print x.l
"Susan Boyle is 50 and alive. Albert Speer is 106 and dead."
Run Code Online (Sandbox Code Playgroud)

编辑

考虑到agf的解决方案,如何再次访问字典?我的意思是,如果我定义__str__方法然后显然我应该定义其他东西来检索字典.请考虑以下示例:

class PClass(dict):
    def __str__(self):
        # code to return the result that I want 

class Foo:
    def __init__(self):
        self.l = PClass({"Susan": ["Boyle", ........ })

>>> x = Foo()
>>> print x.l 
# result that works great
>>> y = x.l["Susan"] # this would not work. How can I achieve it? 
Run Code Online (Sandbox Code Playgroud)

agf*_*agf 22

你需要子类化你正在打印的项目.

from itertools import chain

class PrintableList(list): # for a list of dicts
    def __str__(self):
        return '. '.join(' '.join(str(x) for x in
            chain.from_iterable(zip((item[0], 'is', 'and'), item[1])))
                for item in (item.items()[0] for item in self)) + '.'

class PrintableDict(dict): # for a dict
    def __str__(self):
        return '. '.join(' '.join(str(x) for x in
            chain.from_iterable(zip((item[0], 'is', 'and'), item[1])))
                for item in self.iteritems()) + '.'

class Foo:
   def __init__(self):
      self.d = PrintableDict({"Susan": ("Boyle", 50, "alive"), 
                              "Albert": ("Speer", 106, "dead")})

class Bar:
   def __init__(self):
      self.l = PrintableList([{"Susan": ("Boyle", 50, "alive")}, 
                              {"Albert": ("Speer", 106, "dead")}])

foo = Foo()
print self.d
bar = Bar()
print self.l
Run Code Online (Sandbox Code Playgroud)