Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Advanced Objects Controlling Conversion

Kohei Ashida
Kohei Ashida
4,882 Points

Why is there str(value) in the first def

Kenneth has written the first def in the NumString class like

class NumString:
    def __init__(self, value):
        self.value = str(value)

    def __str__(self):
        return self.value

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)

but why should str(value) be put in the first def? I thought it should be like below lines.

class NumString:
    def __init__(self, value):
        self.value = value    #str() removed

    def __str__(self):
        return str(self.value)    #str() added

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)

What are advantages in writing like Kenneth did?

2 Answers

Steven Parker
Steven Parker
229,744 Points

The purpose of the class is to store numeric values as strings. The modification in the second example would cause it to store the value as a number, but convert it into a string on demand. To complete the modification, you'd need to make changes to the other methods as well.

Technically, the functionality could be reproduced the other way, but if the main intention of the class is to hold a value as a string, only the first example accomplishes that.

Kohei Ashida
Kohei Ashida
4,882 Points

Thanks so much, Steven! I forgot that Kenneth explained that it's to store numeric values as strings as you mentioned.