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 trialSon-Hai Nguyen
2,481 PointsHow to use single underscore?
I know that by using single underscore, we're telling those who reading our script that that method belong to the class or its subclasses themselves rather than its instances. But how to determine if a method should belong to class' instances or just the class and its subclasses themselves?
Thank you guys.
1 Answer
Ben Slivinn
10,156 PointsWhen it comes to variable and method names, the single underscore prefix has a meaning by convention only. This isn’t enforced by Python. Python does not have strong distinctions between “private” and “public” variables like Java does.
A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses.
This is also called name mangling—the interpreter changes the name of the variable in a way that makes it harder to create collisions when the class is extended later.
Good luck!
Son-Hai Nguyen
2,481 PointsSon-Hai Nguyen
2,481 PointsI think you didnt quite get what I meant. I understand that it's merely a name convention only, but I'm wondering how should we decide if a method belong to class' instances or the class itself? Thank you for your answer.