Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python __str__ for an object

Tags:

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?  
like image 654
Shaokan Avatar asked Aug 22 '11 19:08

Shaokan


People also ask

What is the purpose of __ str __ function?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

How do you search for an object in a string in Python?

String find() in Python Just call the method on the string object to search for a string, like so: obj. find(“search”). The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.

Is str an object in Python?

Python str() function object: The object whose string representation is to be returned.

How do you print the value of a object in Python?

Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object. Let's say you only wanted to print the object's instance attributes as well as their values, we can use the vars() function.


1 Answers

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 
like image 59
agf Avatar answered Nov 02 '22 04:11

agf