Prince-linux / python-learning

for learning Python
MIT License
1 stars 0 forks source link

Printing objects #19

Closed lcabrini closed 9 years ago

lcabrini commented 9 years ago

This issue depends on #17

If you create a class, instantiate an object based on this class and try to print it, you get an output that might not always be suitable.

class Person:
    def __init__(self, name):
        self.name = name

p = Person("Chales")
print(p)

Will give output that looks something like this:

<__main__.Person object at 0x7ff6be622518>

But we have a special method str() which we can use to specify how our objects should be printed. For example, if we wanted print(p) to print the name of the person we could do this:

class Person:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

p = Person("Kwaku")
print(p)

Notice how the output has changed. Now add str methods to all the classes you created in src/classes.