DEV Community

Discussion on: The Four Principles of Object Oriented Programming in Python

Collapse
 
amnemonic profile image
Adam Mnemonic

One question:
Is self.__size = "big" private just because __ before size? Would this work differently if we call this variable as size?

Collapse
 
ykarthikeyan profile image
Karthikeyan Y

It is just a convention. It is understood that if we use __ in the beginning of a property name, it should be not be accessed from outside.

Collapse
 
amnemonic profile image
Adam Mnemonic

Yes, at the beginning of my journey with Python I also thought that it is only convention but visibility is also affected.
You can compare output of code using both versions:

When using self.__size (trinket) output is:
I'm a bigfish
I'm a bigfish
I'm a tinyfish

And running same code but using self.size (trinket) will give you output:
I'm a bigfish
I'm a smallfish
I'm a tinyfish

So, although code is technically correct, some explanation would be nice. :)

Thread Thread
 
nimai profile image
Nimai

Wow, I'm surprised you're the first person I've encountered who's talked about this. I just ran this code and it feels like a very important detail 😯