Python Object-Oriented Python Dice Roller Yatzy Scoring

Son-Hai Nguyen
Son-Hai Nguyen
2,481 Points

How 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
Ben Slivinn
10,156 Points

When 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
Son-Hai Nguyen
2,481 Points

I 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.