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

Juneau Lim
Juneau Lim
13,362 Points

Am I understanding subclassing correctly?

I have read this question. I think my understanding is right, but I am not 100% sure.

So, if there was no __init__ method in the subclass, it means that there was no constructor, so even if we declare an object of that class, it calls its superclass, and the actual class becomes its superclass.

The class with only __new__ method only provide functionality(whether with the extra method or only with new itself) but not the class instant.

Is this the case? I have learned OOP with Java, so if there is anything wrong, comparing with Java equivalent will help me understand. Thanks in advance!

1 Answer

Steven Parker
Steven Parker
215,372 Points

Comparing with other languages might not yield the clearest understanding. In other languages, a "constructor" may combine the functionality that is separated in Python into "__new__" and "__init__", but provide less control over the process.

Overriding "__new__" lets you control what is actually returned as the new "instance", and "__init__" establishes the starting conditions (but doesn't return anything).

The Python Reference manual (check it for more details) says this about the difference:

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

Juneau Lim
Juneau Lim
13,362 Points

I see. That makes sense. Still, a bit confused but I think I just have to get used to it by actually using it. Thank you for the explanation!