+ 6

How to make an attribute completely inaccessible?

I have created a class Rational that has protected attributes namely _num and _den. I've been trying to make _num and _den unavailable to the outside world. Further, restrict any other attribute to be created by the user from outside. The latter can be achieved using __slots__. But what to do for former?

23rd Sep 2021, 5:15 PM
abhinav
abhinav - avatar
3 Respostas
+ 6
I am not sure to which extent "inaccessibility" is possible in python. The __ is usually just a marker for the users/ programmers. Oma Falk ?
23rd Sep 2021, 7:01 PM
Lisa
Lisa - avatar
+ 3
Lisa there are a few ways that use descriptors or namedtuple etc. As I went through the source code of decimal module (_pydecimal.py) I found this implemented indeed. The decimal object has attributes _exp, _int and _special which cannot be accessed from outside the class i.e., doing obj._int or obj._int = sth throws error. I'm weak at OOP and so I could not understand these concepts (descriptors, namedtuple etc.) well. If someone here could help from outside the box I'll very thankful!
24th Sep 2021, 1:49 AM
abhinav
abhinav - avatar
+ 1
Google "we are all consenting adults here" and "python".
23rd Sep 2021, 6:02 PM
Simon Sauter
Simon Sauter - avatar