Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

python __str__ for an object

While trying to figure out how BeautifulSoup works, I incidentally learnt the __str__ method (I'm new to python). So if I did not misperceived then the __str__ method helps to shape how the class will be represented if printed out. For instance:

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

>>> x = Foo()
>>> print x
bar

Right? So asserting that I'm right, is it possible to override the __str__ method of a list of dictionaries? I mean say that in class Foo you have:

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

Now is it possible to have the following outcome?

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

EDIT

Considering agf's solution, how can I access the dictionary once again? I mean if I define __str__ method then apparently I should define something else to retrieve the dictionary as it is. Please consider the following example:

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? 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to subclass the item you're pretty-printing.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...