[Tutor] Question

eryksun eryksun at gmail.com
Tue Sep 11 23:09:54 CEST 2012


On Tue, Sep 11, 2012 at 12:08 PM, Ashley Fowler
<afowler2 at broncos.uncfsu.edu> wrote:
>
> I have a question. In a assignment it asks for me to do the following
> below...
>
> if "peek" then print the Student object at the beginning
> 		of the list (using __str__) but don't remove it from
> 		the list;
>
>
> Could you explain what it means?

The __str__ special method of an object will be called when passed to
the built-in str() constructor. This method is required to return a
string.

For example, here's a class with an __str__ method that prints
"calling __str__" to the screen in addition to returning the string
"eggs". This demonstrates some of the ways __str__ is implicitly
called.


    class Spam:
        def __str__(self):
            print("calling __str__")
            return "eggs"


    >>> s = Spam()

    >>> str(s)
    calling __str__
    'eggs'

    >>> "spam and {}".format(s)
    calling __str__
    'spam and eggs'

    >>> print(s)
    calling __str__
    eggs


Make sure __str__ returns a suitable string representation of the
student. The assignment should specify the string formatting of
Student objects.


More information about the Tutor mailing list