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 trialJuneau Lim
13,362 PointsAm 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
231,269 PointsComparing 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
13,362 PointsJuneau Lim
13,362 PointsI 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!