I am wondering wether the title describes whether there is any other use for public attributes in classes than just making it easy for beginners. And then making it rather difficult if they take one step further into python. So what am I actually talking about?
How everything started
As I started to learn python, I was already deep into a project with matlab classes. In the beginning I didn't care much of private or public members of the class so did I neither with python. It was no problem until somebody said to be: "Make everything private!"
That was the point where I tried to understand the mechanic behind "Getter and Setter". I have to say, until now it was worthy.
How I would implement everything from now
I like to present my skeleton of a basic class structure which I would prefer from now:
class Skeleton():
def __init__(self):
self.__x = True
def __getX(self):
return self.__x
def __setX(self, x):
if type(x) == bool:
self.__x = x
x = property(__getX, __setX)
I prefer to do it like this because the access to __x
follows the same syntax as the public declaration, but with the profit of carring about the datatype of __x
and much possible more.
What did I mean with making it difficult
By investigating open source code I discovered very often the usage of "get" functions that are public and also used as this. If this is the case variables will be called by the get function instead by its name. This is okay but much more frustrating if someone (me included) sees there is a better (IMO) way to handle class attributes.
The Conclusion
For me it seems to be "opinion" problem in the community. Referencing on Python name mangling the accepted awnser follows a totaly different approach as everything should be easy as it is. I would confirm this, if first there are no inflational use of "get" functions and second why should you do something the easier (but mangling) way than putting the secure implementation.
I think it is mangling because if somebody uses a class in the future and put some wrong value to an attribute he would never know if it was planned for this or not. If you do it as I described above and put an extra message or warning or even better an exception on the else
the user has the opportunity to understand what he was doing wrong.
So why should I use public from now?
One Last Mention
Since this Idea of coding is not my own I want to refernce the origin, but it is in german so I put on the end: https://www.python-kurs.eu/python3_properties.php