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

__str__ and so on

why do we need to use str , int , ... to return a value, wouldn't a simple code like value = 6 newIStr = str(value) or newInt = int(value) and so on

1 Answer

Steven Parker
Steven Parker
229,732 Points

The functions like "str()" and "int()" are used to convert values from one type to another, but in the process of performing the conversion, the system will use the "magic" methods ("__str__()", "__int__()", etc.) to actually get the object's value in that other form.

The system knows how to convert the built-in types, but it doesn't know how to convert a custom object unless you provide the method for it.

class foo:    # this class just contains a value
    val = 21

class bar:    # this one also has an "__int__" method
    val = 42
    def __int__(self):
        return self.val

f = foo()     # f is a foo object
b = bar()     # b is a bar object

print(int(f)) # taking the int value of f fails
# TypeError: int() argument must be a string, a bytes-like object or a number, not 'foo'

print(int(b)) # but it works just fine for b
# 42