Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Advanced Objects Subclassing Built-ins

Andrew Bickham
Andrew Bickham
1,461 Points

__new__

when using __new__ we use it to override correct? just like with super, but what im unsure of is what exactly are we overriding? when super was introduced we would use super to override the method in the parent class for our code in the sub class but so what are we using __new__ to override? is it the fact that were dealing with str and they're immutable?

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,982 Points

Good question! When a class instance is made it is the __new__ method that creates and returns the new instance. It is the __new__ method that calls __init__ to initialize the instance. This is why the __init__ method does not return an object. It is the self referenced in the __init__ that is returned by the __new__ method.

The ___new__ method is overridden when extending an immutable type to allow changing the object creation arguments before it is created. super() is then used to call the parent’s __new__ method to create the instance.

On terminology, super() doesn’t override the parent method, but rather executes the parent’s method from with the overriding child method.

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

Andrew Bickham
Andrew Bickham
1,461 Points

thank you, ima read over it a couple times and more than likely post back with another question, i appreciate your consist support

Chris Freeman
Chris Freeman
Treehouse Moderator 67,982 Points

If it’s a follow on to this post, I’ll respond to comments here.