Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Public, protected and private attributes accessibility

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...