I have a question about the accessibility of the different access level of class attributes.
I wrote this code:
class struct:
??? def __init__(self, dict):
??????? for key in dict:
??????????? setattr(self, '__'+key, dict[key])
??????? for key in dict:
??????????? setattr(self, '_'+key, dict[key])
??????? for key in dict:
??????????? setattr(self, key, dict[key])
??? def access_data(self):
??????? print(self.a)
??? def access_protected_data(self):
??????? print(self._a)
??? def access_private_data(self):
??????? print(self.__a)
mydict = {'a': 2, 'b': 'abc', 'c': [4]}
q = struct(mydict)
q.a = 4
q.access_data()
q._a = 5
q.access_protected_data()
q.__a = 6
q.access_private_data()
The program will print:
4
5
and sets q.__a = 6
?
I don't understand this behaviour. I would think that the program wouldn't be able to set the q.__a=6 outside of the class, at the same time I would expect the program to be able to print q.__a from a function inside the class.
Could you please explain?
question from:
https://stackoverflow.com/questions/65857093/public-protected-and-private-attributes-accessibility 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…