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

Ben Slivinn
Ben Slivinn
10,156 Points

Could you please explain why are we using self = str.__new__(*args)?

Object-Oriented Python, Subclassing Built-ins.

I tried to play with ReversedStr's new() method and add a loop to accept multiple arguments (rs = ReversedStr(321, 987), and the first argument successfully converted to string type because of str.new() (In my understanding its because str.new()), but the second one isn't. That is when I understood that I don't really get it why you are using str.new().

Sourcecode:

class ReverseStr(str):
    def __new__(*args):
            self = str.__new__(*args) # self is just a variable name.
            self = self[::-1]
            return self

rs = ReverseStr(321)
print(rs)

Thank you!

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Great question!

From https://mail.python.org/pipermail/tutor/2008-April/061426.html:

Use __new__ when you need to control the creation of a new instance. Use __init__ when you need to control initialization of a new instance.

__new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created.

In general, you shouldn't need to override __new__ unless you're subclassing an immutable type like str, int, unicode or tuple.

The *args is used in the __new__ signature to allow an arbitrary number of arguments to be passed in. Using *args again on the call to str.__new__(*args) passes these arbitrary number of arguments on to the parent's method.

By using the call to str.__new__ you get all the parent class attributes and methods.

The __new__() method creates and returns exactly one object. It can not be used to create multiple objects.

Post back if you need more help. Good luck!!!